Associated type requirements

suggest change

Protocols may define associated type requirements using the associatedtype keyword:

associatedtype Element

Protocols with associated type requirements are mostly used as generic constraints (since Swift 5.7 they can also be used as existential types, written any Container):

// Not a concrete type; must be written as an existential.
// let values: any Container

// Allowed: use Container only as a generic constraint.
func use<T: Container>(_ values: 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:

struct Stack<T>: Container {
    // Other Container requirements are omitted.
    // `T` stands in for `associatedtype Element`.
    typealias Element = T
}

(The generic placeholder is named T. Naming it Element would also work, and would shadow the protocol’s associatedtype Element. The compiler can infer that placeholder as the associated type when it is used where Element is required.)

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents