Bird
Raised Fist0
Swiftprogramming~20 mins

For-in with where clause in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift For-in Where Clause Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of a Swift for-in loop with where clause filtering even numbers
What will be printed by this Swift code?
let numbers = [1, 2, 3, 4, 5, 6]
for num in numbers where num % 2 == 0 {
    print(num)
}
Swift
let numbers = [1, 2, 3, 4, 5, 6]
for num in numbers where num % 2 == 0 {
    print(num)
}
A
2
4
6
B
1
3
5
C
1
2
3
4
5
6
DNo output, syntax error
Attempts:
2 left
💡 Hint
The where clause filters elements before the loop body runs.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Swift for-in loop with where clause
Which option correctly fixes the syntax error in this code?
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits where fruit.hasPrefix("a")
    print(fruit)
Swift
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits where fruit.hasPrefix("a")
    print(fruit)
A
Remove the where clause:
for fruit in fruits {
    print(fruit)
}
B
Change 'where' to 'if':
for fruit in fruits if fruit.hasPrefix("a") {
    print(fruit)
}
C
Add a colon after the where clause:
for fruit in fruits where fruit.hasPrefix("a"): {
    print(fruit)
}
D
Add curly braces around the loop body:
for fruit in fruits where fruit.hasPrefix("a") {
    print(fruit)
}
Attempts:
2 left
💡 Hint
Swift requires braces for loop bodies with multiple lines or where clauses.
❓ optimization
advanced
2:00remaining
Optimize filtering in a Swift for-in loop with where clause
Given this code:
let numbers = Array(1...1000)
var sum = 0
for num in numbers where num % 5 == 0 {
    sum += num
}

Which option is the most efficient way to calculate the sum of multiples of 5?
Swift
let numbers = Array(1...1000)
var sum = 0
for num in numbers where num % 5 == 0 {
    sum += num
}
A
Use stride to iterate only multiples of 5:
for num in stride(from: 5, through: 1000, by: 5) {
    sum += num
}
B
Filter first then loop:
for num in numbers.filter({ $0 % 5 == 0 }) {
    sum += num
}
CKeep the original code as it is the most efficient.
DUse a while loop to check each number and add if divisible by 5.
Attempts:
2 left
💡 Hint
Avoid checking every number when you can jump directly to multiples.
🔧 Debug
advanced
2:00remaining
Debug why this Swift for-in loop with where clause prints no output
Consider this code:
let words = ["Swift", "is", "fun"]
for word in words where word.count > 10 {
    print(word)
}

Why does it print nothing?
Swift
let words = ["Swift", "is", "fun"]
for word in words where word.count > 10 {
    print(word)
}
AThe print statement is outside the loop body due to missing braces.
BThe syntax of the where clause is incorrect, causing the loop to skip printing.
CNo word in the array has more than 10 characters, so the where clause filters out all elements.
DThe array is empty, so the loop never runs.
Attempts:
2 left
💡 Hint
Check the condition in the where clause against the array elements.
🧠 Conceptual
expert
3:00remaining
Understanding the behavior of multiple where clauses in nested for-in loops
What will be the output of this Swift code?
let numbers = [1, 2, 3]
let letters = ["a", "b", "c"]
for num in numbers where num % 2 != 0 {
    for letter in letters where letter != "b" {
        print("\(num)\(letter)")
    }
}
Swift
let numbers = [1, 2, 3]
let letters = ["a", "b", "c"]
for num in numbers where num % 2 != 0 {
    for letter in letters where letter != "b" {
        print("\(num)\(letter)")
    }
}
A
1a
1b
1c
3a
3b
3c
B
1a
1c
3a
3c
C
2a
2c
DNo output due to syntax error
Attempts:
2 left
💡 Hint
Both loops filter elements with their own where clauses.

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