This can be done for:
- Functions- Methods- Initializers- Structures- Enumerations- Classes
Each one of these has an angle bracket that specifies some type.
Let’s see how generics work by implementing a Stack data structure. A Stack is a last-in-first-out collection that helps organizes data in a particular order.
Here is the coding, which no generics are being used. We can use the Swift type “Any” to support any type.
We can push in or pop out any type in this Stack without making sure to restrict beforehand the Stack to a specific type and to leverage compile time checks to guarantee that the Stack will not contain extraneous types, so it occurs a small performance cost. That’s where generics come in. We often name it T, or U, or Element as following:
We can also add an initializer from an array Literal.
Now we can use inference to write something like this:
What’s important to note here is that this is just a shorthand for what the compiler inferred. It still knows that it’s a stack of Ints and it uses this information at compile time for better safety and performance.
We can make a generic type conditionally conforms to a protocol by writing constraints when extending the type. For example,
Inside a protocol, we declare an associated type with any constraints with the keyword associatedtype, and then in the generic type being constrained by this protocol, we can explicitly declare the type that we are using for the associated type with typealias, or we can let the compiler infer it. Let’s see this in action.
Now we’re going to make the same Distribution protocol but with a twist. The random number facility in Swift allows us to specify a generator that is used each time a random number is produced. By default SystemRandomNumberGenerator returns a generator type that conforms to the protocol RandomNumberGenerator. This type is mutated each time, and produces a non-repeatable and cryptographically secure random number.
Constrain Associated Type
We can even define our own protocol, for example, let’s define Sortable.