Associated type requirements
suggest changeProtocols may define associated type requirements using the associatedtype
keyword:
associatedtype Element
Protocols with associated type requirements can only be used as generic constraints:
NOT allowed<T: Container>T<T: Container>T
A type which conforms to the protocol may satisfy an associatedtype
requirement implicitly, by providing a given type where the protocol expects the associatedtype
to appear:
T
(Note that to add clarity to this example, the generic placeholder type is named T
– a more suitable name would be Element
, which would shadow the protocol’s associatedtype Element
. The compiler will still infer that the generic placeholder Element
is used to satisfy the associatedtype Element
requirement.)
An associatedtype
may also be satisfied explicitly through the use of a typealias
:
typealias Element = TElement
The same goes for extensions:
// Expose an 8-bit integer as a collection of boolean values (one for each bit).
extension UInt8: Container {
// as noted above, this typealias can be inferred
typealias Element = Bool
var count: Int { return 8 }
subscript(index: Int) -> Bool {
get {
precondition(0 <= index && index < 8)
return self & 1 << UInt8(index) != 0
}
set {
precondition(0 <= index && index < 8)
if newValue {
self |= 1 << UInt8(index)
} else {
self &= ~(1 << UInt8(index))
}
}
}
}
If the conforming type already satisfies the requirement, no implementation is needed:
extension Array: Container {} // Array satisfies all requirements, including Element