Type Constraints

One of the most important things to keep in mind when writing generic functions and data types is that, by default, you do not know anything about the concrete type that is going to be used. You created stacks of Int and String, but you could also create stacks of any other type at all. The practical impact of this lack of knowledge is that there is very little you can do with the value of a placeholder type. For example, you cannot check if two of them are equal; this code would not compile:

func checkIfEqual<T>(first: T, _ second: T) -> Bool {
    return first == second
}

This function could be called with any type at all, including types for which equality does not make sense, such as closures. (It is hard to ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.