The Basics of Swift Generics in 3 Mins

Generics allow a type or method to operate on objects of various types while providing compile-time type safety”.

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.

Protocol Constraints

We can make a generic type conditionally conforms to a protocol by writing constraints when extending the type. For example,

Associated Type

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.

Generic Protocol

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

Numeric locks down Value to be constrained to the protocol Numeric(a type with values that support multiplication)

Conditional Conformance

We can even define our own protocol, for example, let’s define Sortable.

Notice: Integer nums return max and sorted, but bools cannot because bools are not comparable.


On a side note, I’d like to communicate with you via claps here. So If you like this story, please reward me 1–3 👏 (PS Holding on clicking the 👏 without lifting your finger can clap in a row.); If you are following me and looking forward to my visit to your story too, please give me 5 👏 to let me know️ ❤ ️

A life enthusiast🇹🇼