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."
In this page:
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
for number in 1...10 where number % 3 == 0 {
print("Multiple of 3: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
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
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))")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing the loop-level
whereclause (which filters iterations) withswitchcasewhere(which adds a match condition) -- they look similar but apply differently. - Writing a separate
ifinside the loop body when awhereclause on the loop itself would be cleaner and skip non-matching elements entirely. - Forgetting
wherein 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
whereclause on afor-inloop filters which iterations run their body. - A
whereclause on aswitchcase adds an extra condition beyond just pattern matching. wheremakes 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: