Swift version: 5.10
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.
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.