NEW: Master Swift design patterns with my latest book! >>

What is a protocol associated type?

Written by Paul Hudson    @twostraws

Associated types are a powerful way of making protocols generic, but they can be a bit confusing at first. In essence, the mark holes in protocols that must be filled by whatever types conform to those protocols.

Let’s start with a simple example: an ItemStoring protocol that can store items in an array. What type those items are depends on whatever conforms to the protocol, but we can still use them inside the protocol and any extensions.

Here’s the basic protocol:

protocol ItemStoring {
    associatedtype DataType

    var items: [DataType] { get set}
    mutating func add(item: DataType)
}

As you can see, it requires that conforming types provide an items array that holds an array of whatever is used to fill the DataType hole, and also a mutating method to add items of that type.

That mutating method is probably going to be the same for all conforming types, so we can write a protocol extension that provides a default implementation:

extension ItemStoring {
    mutating func add(item: DataType) {
        items.append(item)
    }
}

Finally we can create a NameDatabase struct that conforms to the ItemStoring protocol like this:

struct NameDatabase: ItemStoring {
    var items = [String]()
}

Swift is smart enough to realize that String is being used to fill the hole in the associated type, because the items array must be whatever DataType is.

That’s all the code written, so you can go ahead and use NameDatabase:

var names = NameDatabase()
names.add(item: "James")
names.add(item: "Jess")

Available from iOS – learn more in my book Swift Design Patterns

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

Click here to visit the Hacking with Swift store >>