Bird
Raised Fist0
Swiftprogramming~10 mins

For-in with where clause in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - For-in with where clause
Start loop over collection
↓
Check where condition
↓
Execute loop body
↓
Next element or end loop
The loop goes through each item, checks the condition after 'where', runs the body only if true, otherwise skips to next.
Execution Sample
Swift
let numbers = [1, 2, 3, 4, 5]
for num in numbers where num % 2 == 0 {
    print(num)
}
Loops over numbers, printing only even ones (where condition filters items).
Execution Table
IterationnumCondition (num % 2 == 0)ActionOutput
11FalseSkip iteration
22TrueExecute loop body2
33FalseSkip iteration
44TrueExecute loop body4
55FalseSkip iteration
💡 All elements checked; loop ends after last element.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
numnil123455
Key Moments - 2 Insights
Why does the loop skip some numbers instead of printing them?
Because the where clause filters items. Only numbers where num % 2 == 0 (even numbers) run the loop body, as shown in execution_table rows 1,3,5 where condition is False and action is skip.
Does the loop stop early when the condition is false?
No, the loop continues checking all elements. It only skips executing the body for elements that don't meet the condition, as seen in execution_table where all iterations run but some skip the body.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' at iteration 4?
A3
B2
C4
D5
💡 Hint
Check the 'num' column in execution_table row for iteration 4.
At which iteration does the condition 'num % 2 == 0' become true for the first time?
AIteration 2
BIteration 1
CIteration 3
DIteration 5
💡 Hint
Look at the 'Condition' column in execution_table to find first True.
If the where clause was removed, what would change in the execution table?
AThe loop would skip all iterations.
BAll iterations would execute the loop body and print all numbers.
COnly odd numbers would be printed.
DThe loop would run zero times.
💡 Hint
Without where clause, no filtering happens, so all elements run the loop body.
Concept Snapshot
for item in collection where condition {
    // code runs only if condition true
}

- Loops over collection
- 'where' filters items
- Body runs only if condition true
- Skips items failing condition
- Loop continues through all elements
Full Transcript
This visual execution shows a Swift for-in loop with a where clause. The loop goes through each number in the array. For each number, it checks if the number is even (num % 2 == 0). If true, it runs the loop body and prints the number. If false, it skips printing and moves to the next number. The variable 'num' changes each iteration to the current number. The loop does not stop early; it checks all numbers. This filtering behavior is controlled by the where clause. The execution table tracks each step, showing which numbers print and which skip. This helps beginners see how the where clause filters items in a loop.

Practice

(1/5)
1. What does the where clause do in a for-in loop in Swift?
easy
A. It repeats the loop twice for each item.
B. It changes the type of the loop variable.
C. It filters items so the loop runs only on those that meet the condition.
D. It stops the loop after the first item.

Solution

  1. Step 1: Understand the role of where in a loop

    The where clause adds a condition to filter items during iteration.
  2. Step 2: Effect on loop execution

    Only items that satisfy the where condition are processed in the loop.
  3. Final Answer:

    It filters items so the loop runs only on those that meet the condition. -> Option C
  4. Quick Check:

    where filters loop items [OK]
Hint: Remember: where filters items in the loop [OK]
Common Mistakes:
  • Thinking where changes variable type
  • Assuming it repeats the loop multiple times per item
  • Believing it stops the loop early
2. Which of the following is the correct syntax for using a where clause in a Swift for-in loop?
easy
A. for item where item.isActive in items { print(item) }
B. for item in items where item.isActive { print(item) }
C. for item in items if item.isActive { print(item) }
D. for item in items; where item.isActive { print(item) }

Solution

  1. Step 1: Recall correct for-in where syntax

    The correct syntax places where after the sequence: for variable in sequence where condition.
  2. Step 2: Check each option

    Only for item in items where item.isActive { print(item) } matches the correct syntax. The other options have misplaced or incorrect keywords: where before in, if instead of where, or a semicolon before where.
  3. Final Answer:

    for item in items where item.isActive { print(item) } -> Option B
  4. Quick Check:

    Correct where syntax [OK]
Hint: Put where right after in sequence [OK]
Common Mistakes:
  • Placing where before in
  • Using if instead of where
  • Adding semicolon before where
3. Given the array let numbers = [1, 2, 3, 4, 5], what will this code print?
for num in numbers where num % 2 == 0 {
    print(num)
}
medium
A. 2 4
B. 1 2 3 4 5
C. 1 3 5
D. No output

Solution

  1. Step 1: Understand the loop and condition

    The loop iterates over numbers and prints only those where num % 2 == 0, meaning even numbers.
  2. Step 2: Identify even numbers in the array

    From [1, 2, 3, 4, 5], the even numbers are 2 and 4.
  3. Final Answer:

    2 4 -> Option A
  4. Quick Check:

    Print even numbers = 2 4 [OK]
Hint: Check condition filters even numbers only [OK]
Common Mistakes:
  • Printing odd numbers instead
  • Printing all numbers ignoring where
  • Expecting no output
4. What is wrong with this Swift code?
let names = ["Anna", "Bob", "Cara"]
for name where name.hasPrefix("A") in names {
    print(name)
}
medium
A. The where clause is placed before in incorrectly.
B. The array names is not declared properly.
C. The hasPrefix method does not exist.
D. The loop variable name should be a constant.

Solution

  1. Step 1: Check the for-in where syntax

    The where clause must come after in sequence, not before.
  2. Step 2: Identify the syntax error

    The code places where before in names, which is invalid syntax.
  3. Final Answer:

    The where clause is placed before in incorrectly. -> Option A
  4. Quick Check:

    where must follow in [OK]
Hint: Always put where after in [OK]
Common Mistakes:
  • Placing where before in
  • Assuming hasPrefix is invalid
  • Thinking loop variable must be var
5. You have a list of user records as dictionaries:
let users = [
  ["name": "Alice", "age": 25],
  ["name": "Bob", "age": 17],
  ["name": "Cara", "age": 30]
]

Using a for-in loop with a where clause, how do you print only the names of users who are 18 or older?
hard
A. for user in users { if user["age"] >= 18 { print(user["name"]!) } }
B. for user where (user["age"] as? Int ?? 0) >= 18 in users { print(user["name"]!) }
C. for user in users if (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) }
D. for user in users where (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) }

Solution

  1. Step 1: Use correct for-in where syntax

    The where clause must come after in users to filter users by age.
  2. Step 2: Check type casting and condition

    Use safe cast as? Int with default 0, then check if age >= 18.
  3. Step 3: Print the name safely

    Access user["name"]! to print the name string.
  4. Final Answer:

    for user in users where (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) } -> Option D
  5. Quick Check:

    Correct for-in where with safe cast [OK]
Hint: Put where after in users with safe cast [OK]
Common Mistakes:
  • Placing where before in
  • Using if instead of where
  • Not casting age safely
  • Forgetting to unwrap name
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard