A Swift Look at Protocols with Associated Types

When I first saw the term “associated types” on Twitter and around the inter-webs, I honestly just ignored it. It seemed very high level.

But then two things happened almost at the same time. I used a protocol with an associated type without even knowing what it was as I was catching up on blogging! And I watched @alexisgallagher’s talk about Protocols with Associated Types from the Functional Swift Conference earlier this month.

Both of these things brought a lot of clarity to me about a complicated topic and helped me understand this Swift Evolution proposal. So I’d like to write down my initial understanding of Protocols with Associated Types – mostly what they are and how to use them.

A Placeholder for an Unknown Type

I really loved @alexisgallagher‘s definition of associated types as a placeholder for an unknown type.

The idea is that you can define a protocol with functions that take in a type that is defined by the object that uses that protocol:

So now, we can have different animals that have different types of Food:

As you can see, all the animals above take in a completely different food source, but they still conform to the Animal protocol!

Constraining Protocol Extensions

This means that if you want to have a protocol extension with a default implementation for the eat function, you need to specify the type:

Conclusion

I’m still learning how to use protocols with associated types – after all, I just really learned about them. But they definitely seem powerful. You can view a really great “real-life” example in my previous blog post: Protocol-Oriented Segue Identifiers in Swift.

In addition, to learn more about the limitations of Protocols with Associated Types (aka where you might run into big problems) make sure to watch @alexisgallagher’s talk:

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.