associatedtype & generic protocols
Define protocols with associatedtype , see how conforming types bind them, and use generic functions with protocol constraints.
Why associated types?
Protocols can be generic via associatedtype. Conforming types bind the placeholder to a concrete type.
Protocol with associatedtype
associatedtype Item acts like a type parameter. Requirements can use it in methods, subscripts, and properties.
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(index: Int) -> Item { get }
}All lessons in this course
- associatedtype & generic protocols
- Type erasure patterns (AnySequence/AnyIterator)
- When to use existentials (any P) vs generics