← 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."
Syntax
swift
for item in collection where condition {
    // only items matching the condition
}

switch value {
case let x where condition:
    // code
default: break
}

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
// Loop over `1...10 where number % 3 == 0`, binding each item to `number`
for number in 1...10 where number % 3 == 0 {
    // Print "Multiple of 3: \(number)" to the console
    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
// Declare a constant `point`, set to `(2, 2)`
let point = (2, 2)
// Switch on `point` and branch by case
switch point {
// Case: `let (x, y) where x == y`
case let (x, y) where x == y:
    // Print "Point is on the diagonal" to the console
    print("Point is on the diagonal")
// Case: `let (x, y)`
case let (x, y):
    // Print "Point at (\(x), \(y))" to the console
    print("Point at (\(x), \(y))")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.