Swift Academy · Lesson

where Clauses on Functions

Add fine-grained constraints to generic functions.

Lesson 2 of 413 steps

where Clauses on Functions is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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])))

Protocol Requirement on Element

You can require the element conform to a protocol rather than be one exact type, which is more flexible.

func joinAll<C: Collection>(_ c: C) -> String
    where C.Element: CustomStringConvertible {
    c.map { $0.description }.joined(separator: ", ")
}
print(joinAll([1, 2, 3]))

where Comes After Signature

The where clause sits between the return type and the function body. Constraints inside <> and the where clause work together.

func maxElement<C: Collection>(_ c: C) -> C.Element?
    where C.Element: Comparable {
    c.max()
}
print(maxElement([4, 9, 2])!)

Relating Two Type Parameters

A where clause can tie the element types of two different generics together with ==.

func combine<A: Collection, B: Collection>(_ a: A, _ b: B) -> [A.Element]
    where A.Element == B.Element {
    Array(a) + Array(b)
}
print(combine([1, 2], Set([3])))

Multiple where Conditions

List several requirements separated by commas to express compound constraints.

func report<C: Collection>(_ c: C)
    where C.Element: Comparable, C.Element: CustomStringConvertible {
    if let m = c.max() { print("max:", m.description) }
}
report([5, 1, 9])

Constraining Nested Associated Types

You can reach deeper, for example requiring the element of an element, when working with nested collections.

func flatten<C: Collection>(_ c: C) -> [Int]
    where C.Element: Collection, C.Element.Element == Int {
    c.flatMap { Array($0) }
}
print(flatten([[1, 2], [3]]))

where with Equatable Elements

Requiring Equatable elements lets you search a generic collection.

func indexOf<C: Collection>(_ x: C.Element, in c: C) -> C.Index?
    where C.Element: Equatable {
    c.firstIndex(of: x)
}
if let i = indexOf(2, in: [1, 2, 3]) { print("found") }

Generic Methods with where

Methods inside generic types use where too, often to add behavior only for certain element types.

struct Wrap<T> {
    let items: [T]
    func total() -> Int where T == Int { items.reduce(0, +) }
}
print(Wrap(items: [1, 2, 3]).total())

Readability Benefit

Complex constraints read more clearly in a where clause than crammed into the angle brackets, especially with several associated-type conditions.

func first<C: Collection>(_ c: C) -> String
    where C.Element: CustomStringConvertible {
    c.first.map { $0.description } ?? "empty"
}
print(first([10, 20]))

where in the Standard Library

Methods like joined() on sequences of sequences use where clauses internally to express their requirements precisely.

let nested = [[1, 2], [3, 4]]
print(Array(nested.joined()))

Quick Check

Test your understanding of where clauses on functions.

Recap

where clauses let you constrain a generic's associated types: require an element to be a specific type (== Int), conform to a protocol (: Comparable), relate two parameters' elements, or reach into nested associated types. They live after the signature and keep complex constraints readable.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “where Clauses on Functions” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “where Clauses on Functions”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “where Clauses on Functions”?

Add fine-grained constraints to generic functions. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “where Clauses on Functions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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