FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to constrain a protocol associated type

Swift version: 5.4

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 a protocol must specify the id of their object and also what type that ID must be:

protocol Identifiable1 {
    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 Identifiable2 {
    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.

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

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

Available from iOS 8.0

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 Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) 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 Server-Side Swift (Kitura Edition) 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.