where Clauses on Functions
Add fine-grained constraints to generic functions.
Beyond Simple Constraints
A constraint like <T: Collection> describes T itself. But sometimes you need to constrain T's associated types, such as its Element. That is what a where clause does.
func sumInts<C: Collection>(_ c: C) -> Int where C.Element == Int {
c.reduce(0, +)
}
print(sumInts([1, 2, 3]))Same-Type Requirement
where C.Element == Int requires the collection's elements to be exactly Int, enabling integer-specific work.
func describe<C: Collection>(_ c: C) -> String where C.Element == Int {
"Sum is " + String(c.reduce(0, +))
}
print(describe(Set([1, 2, 3])))All lessons in this course
- Type Parameter Constraints
- where Clauses on Functions
- Constraining Associated Types
- Generic Subscripts and Extensions