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:


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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Nasser Ali

    nice post!
    I just want to add that you don’t need StringLiteralConvertible in this case.
    cheers 🙂

  • MrJre

    I’m curious if this would be applicable to your MVVM experiment. When having several different cells taking different ViewModels, you would probably have to create a protocol with associated type?
    The one thing I didn’t figure out yet is the actual dequeuing of the cells, and setting the right configuration

  • ismail şimşek

    it is very good and well writen article I have ever read about protocols and generics. thank you very much. that is clear for me now.

  • Vince O’Sullivan

    And then along comes Swift 3 and deprecates this usage of “typealias”, replacing it with “associatedtype”.

    • Durai amuthan

      Oh is it ?