Discover Generics in Swift


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


You’ve heard that Generics are a very powerful feature of Swift, but you're not entirely sure how they work? 🤨

Don’t worry! I’ve got you covered! 😌

In just a few paragraphs I’ll explain everything you need to start using Generics in your own code!

Let's start with this piece of code:

As you can see, I’ve implemented a data structure to store integers in a Stack.

However, I can only store integers inside this Stack.

Meaning that if I want to store another type, for instance String, I will need to implement a new version of my Stack:

And it will be the same thing if I want to store a custom type in my Stack 😰

Of course, this approach is not scalable at all, and we would like to have a mechanism to define a single Stack that would work with any kind of values.

And as you can imagine, this where Generics come into play!

So let’s go back to my Stack of integers.

I’m going to update my code to introduce a generic type called Element:

This generic type can be seen as a type argument, that we will pass to the Stack to let it know which type it can store!

Now, all that’s left to do is actually use the generic type Element inside the implementation of the Stack:

Finally, we can use our generic type to store different types of elements in our Stack!

That’s it, we’ve covered the basics of how Generics work in Swift 🥳

Thanks to this feature, we were able to define a single type that will be able to work with different types of values, depending on the generic type we provide it 👌

Here’s the code if you want to experiment with it!

struct Stack<Element> {
    private var values = [Element]()

    mutating func push(_ value: Element) {
        values.append(value)
    }

    mutating func pop() -> Element? {
        return values.removeLast()
    }
}

let stackOfInt = Stack<Int>()
let stackOfString = Stack<String>()
let stackOfPerson = Stack<Person>()
Previous
Previous

How to write your first API call

Next
Next

Discover Property Wrappers in Swift