What is an associated type in a protocol?
The idea
An associatedtype is a type placeholder inside a protocol. The protocol states that such a type exists and what constraints it satisfies, and each conforming type supplies its concrete type (explicitly via typealias or inferred from signatures). Sequence.Element, Collection.Index and IteratorProtocol.Element work this way.
protocol Container<Item> {
associatedtype Item: Equatable
var count: Int { get }
mutating func append(_ item: Item)
subscript(i: Int) -> Item { get }
}
struct IntStack: Container {
private var items: [Int] = []
var count: Int { items.count }
// Item = Int is inferred from the signature
mutating func append(_ item: Int) { items.append(item) }
subscript(i: Int) -> Int { items[i] }
}
func contains<C: Container>(_ c: C, _ x: C.Item) -> Bool {
(0..<c.count).contains { c[$0] == x }
}
// Swift 5.7+: primary associated type
func sum(_ c: some Container<Int>) -> Int {
(0..<c.count).reduce(0) { $0 + c[$1] }
}
let boxes: [any Container<Int>] = [IntStack()]
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep