0Pricing
Swift Academy · Lesson

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

  1. associatedtype & generic protocols
  2. Type erasure patterns (AnySequence/AnyIterator)
  3. When to use existentials (any P) vs generics
← Back to Swift Academy