Associated Types
An associated type is like a placeholder name a protocol uses for "some type I need, but I'll let each conformer decide exactly what it is."
Declaring a Protocol with an Associated Type
associatedtype lets a protocol describe a requirement in terms of a placeholder type, which each conforming type specifies concretely.
Example: Declaring a Protocol with an Associated Type
protocol Container {
associatedtype Item
mutating func add(_ item: Item)
var count: Int { get }
}
struct IntContainer: Container {
var items: [Int] = []
mutating func add(_ item: Int) {
items.append(item)
}
var count: Int {
return items.count
}
}
var container = IntContainer()
container.add(5)
container.add(10)
print("Count: \(container.count)")
Login to try C/C++/Java/PHP code in the editor
Swift Infers the Associated Type
Swift automatically infers the concrete type used for Item just from how the conforming type implements add(_:), without needing an explicit typealias.
Example: Swift Infers the Associated Type
protocol Container {
associatedtype Item
mutating func add(_ item: Item)
}
struct StringContainer: Container {
var items: [String] = []
mutating func add(_ item: String) {
items.append(item)
}
}
var container = StringContainer()
container.add("hello")
print(container.items)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing an associated type (a placeholder used inside a protocol) with a generic function's placeholder (used in a function or type declaration).
- Trying to use a protocol with an associated type as a plain variable's type directly (e.g.
var x: Container); it must be used generically or withsome/any. - Forgetting Swift can often infer the concrete associated type automatically from how the conforming type implements the protocol's requirements.
Chapter Summary
associatedtypedeclares a placeholder type used within a protocol's requirements.- Each conforming type fills in the associated type with a concrete type of its choosing.
- Protocols with associated types can't be used as plain standalone variable types without
someorany. - Associated types make protocols flexible enough to describe generic containers and behaviors.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: