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

How to constrain a protocol associated type

Paul Hudson       @twostraws

Protocol associated types let you add a huge amount of flexibility to your protocols, but sometimes you want a little less flexibility. For example, you might say that all types conforming to an Identifiable protocol must specify the id of their object and also what type that ID must be:

protocol Identifiable {
    associatedtype ID
    var id: ID { get set }
}

With that code, ID could be anything – a String, an Int, a UILabel, and so on. However, you might find you need to apply some constraints to that type: perhaps you need to use it as a dictionary key (Hashable), or sort it in an array (Comparable).

To make this work, Swift lets us apply constraints to associated types: “it can be any type, as long as that type conforms to…”. For example, this forces ID to conform to Hashable:

protocol Identifiable {
    associatedtype ID: Hashable
    var id: ID { get set }
}

Because Hashable inherits from Equatable we can now be sure that any types used for ID can be compared using == and also used as keys in dictionaries.

Available from iOS 8.0

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.

Become a Swift expert

I wrote a book called Pro Swift that's dedicated to helping you master the Swift language, and it includes seven hours of video demonstrating each technique!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>