Protocol Associated Type

Protocol associated type is a very useful tool to add to your Swift toolkit. In order to fully understand and appreciate it, we must briefly touch on how a normal protocol works.

As you can see below, the Events protocol declares a string type for the events array.

protocol Events {
  var events: [String] { get set }

Therefore, the conforming type MeetupEvents struct can simply implement the events array as long as it uses the type declared in the protocol. What if you want more flexibility over the type and perhaps have the conforming types decide the type later on? This is where Protocol Associated Type comes in!

struct MeetupEvents: Events {
  var events = ["iOSoho", "Brooklyn Swift"]

You can think of a protocol associated type as a generic placeholder for declaring protocols in Swift without specifying the type upfront. The conforming type would declare an array of whatever type to fill EventType later on and implement the add function.

protocol Events {
  associatedtype EventType

  var events: [EventType] { get set }
  mutating func add(event: EventType)

Adding an extension to this protocol allows you to create a default implementation of the add function.

extension Events {
   mutating func add(event: EventType) {

We create a struct to conform to Events and Swift connects the dots as the expected array could be of any type.

struct MeetupEvents: Events {
    var events = [String]()  

Lastly, we want to implement the add function after creating an instance of MeetupEvents in order to fully conform to the protocol.

var meetupEvents = MeetupEvents()
meetupEvents.add(event: "iOSoho")
meetupEvents.add(event: "Brooklyn Swift") 

Et voilà ! Now you can declare protocols without constraining it to a type upfront and give conforming types more flexibility. What do you think? Let me know in the comments below.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s