UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

What is a protocol associated type?

Swift version: 5.6

Paul Hudson    @twostraws   

Associated types are a powerful way of making protocols generic, but they can be a bit confusing at first. In essence, they 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")
Hacking with Swift is sponsored by Proxyman

SPONSORED Proxyman: A high-performance, native macOS app for developers to easily capture, inspect, and manipulate HTTP/HTTPS traffic. The ultimate tool for debugging network traffic, supporting both iOS and Android simulators and physical devices.

Start for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

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

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.