O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 whether 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required