Type Parameter Constraints
Require conformance on generic parameters.
Generics Recap
A generic function uses a type parameter like <T> so it works with many types. But unconstrained T can only be passed around, not inspected. Constraints unlock capabilities.
func identity<T>(_ x: T) -> T { x }
print(identity(5))
print(identity("hi"))The Comparable Constraint
Writing <T: Comparable> guarantees values of T support <, >, and friends, so you can compare them.
func largest<T: Comparable>(_ a: T, _ b: T) -> T {
a > b ? a : b
}
print(largest(3, 9))
print(largest("apple", "pear"))All lessons in this course
- Type Parameter Constraints
- where Clauses on Functions
- Constraining Associated Types
- Generic Subscripts and Extensions