Constraining Associated Types
Limit associated types in generic contexts.
Associated Types Recap
A protocol can declare an associated type with associatedtype, a placeholder a conforming type fills in. Element in a container protocol is the classic example.
protocol Container {
associatedtype Item
var count: Int { get }
func item(at i: Int) -> Item
}Conforming with a Concrete Type
A conforming type fixes the associated type, often inferred from how it is used.
protocol Container {
associatedtype Item
func item(at i: Int) -> Item
}
struct IntBox: Container {
let values: [Int]
func item(at i: Int) -> Int { values[i] }
}
print(IntBox(values: [10, 20]).item(at: 1))All lessons in this course
- Type Parameter Constraints
- where Clauses on Functions
- Constraining Associated Types
- Generic Subscripts and Extensions