Just figured I’d write something simple about generics just to get this blog going.
First, I’ll demonstrate the situation without generics. A Swift without generics would use structs similar to this:
Now, clearly, this Stack implementation is very inconvenient. If you create a stack and fill it up, it doesn’t keep track of the type it holds. Worse yet, it doesn’t tell you what it returns when you pop off the top element.
In order to use someType, you’d have to typecast it:
This is not good programming. A (bad) solution would be to make your Stack pertain to particular types. IE we could write these two Stacks:
This is, perhaps, even worse than the original situation. Now we have to write a new Stack for each and every type we need a Stack for.
Fortunately, we have generics. A generic Stack gives us the ability to let the compiler know that the Stack will hold a particular type in it’s array, take the same type for the argument for push and return the same type for pop.
This is how Arrays, Dictionaries, Sets etc are implemented in the Swift standard library. Generics allows a struct/class author to implement a type once instead of implementing it for each and every type he’d like to use it for.