0Pricing
Swift Academy · Lesson

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

  1. Type Parameter Constraints
  2. where Clauses on Functions
  3. Constraining Associated Types
  4. Generic Subscripts and Extensions
← Back to Swift Academy