← Back to Swift Course | Chapter 3: Control Flow | Lesson 7 of 8

The where Clause

A where clause adds an extra condition to something, like saying "loop through these, but only the ones that also pass this test."

where in a for-in Loop

Adding where after the loop variable filters which elements actually execute the loop body, skipping ones that don't satisfy the condition.

Example: where in a for-in Loop

markup
for number in 1...10 where number % 3 == 0 {
    print("Multiple of 3: \(number)")
}

where in a switch Case

A case in a switch can add a where clause to require an additional condition beyond simply matching the value's shape.

Example: where in a switch Case

markup
let point = (2, 2)
switch point {
case let (x, y) where x == y:
    print("Point is on the diagonal")
case let (x, y):
    print("Point at (\(x), \(y))")
}
Common Mistakes
  1. Confusing the loop-level where clause (which filters iterations) with switch case where (which adds a match condition) -- they look similar but apply differently.
  2. Writing a separate if inside the loop body when a where clause on the loop itself would be cleaner and skip non-matching elements entirely.
  3. Forgetting where in a for-loop still iterates every element -- it just skips the body for non-matching ones, it doesn't filter the underlying collection.
Chapter Summary
  • A where clause on a for-in loop filters which iterations run their body.
  • A where clause on a switch case adds an extra condition beyond just pattern matching.
  • where makes filtering conditions read naturally as part of the loop or case header.
  • It's especially useful with pattern matching, generics, and protocol constraints (seen more in later chapters).
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.