Constraints (where), type inference
Constrain generic code using where (e.g., Equatable/Comparable or Element constraints) and see how Swift infers generic types at call sites.
Why constraints?
Add constraints so generic code uses certain operations (like == or <). Swift's type inference then picks concrete types at calls.
Equatable constraint
where T: Equatable permits equality checks. Without it, == is not available for any T.
// Find the first index of value in an array of T
func indexOf<T>(_ value: T, in array: [T]) -> Int? where T: Equatable {
for (i, x) in array.enumerated() {
if x == value { return i } // allowed because T: Equatable
}
return nil
}
print(indexOf(3, in: [1,2,3,2]) ?? -1) // 2
print(indexOf("b", in: ["a","b","c"]) ?? -1) // 1All lessons in this course
- Generic functions & types
- Constraints (where), type inference
- Generic algorithms on collections