Bird
Raised Fist0
Swiftprogramming~20 mins

For-in loop with collections in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift For-in Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a for-in loop over an array
What is the output of this Swift code?
let numbers = [1, 2, 3, 4]
var result = 0
for num in numbers {
    result += num
}
print(result)
Swift
let numbers = [1, 2, 3, 4]
var result = 0
for num in numbers {
    result += num
}
print(result)
A1234
B24
C10
DError: Cannot add Int to Int
Attempts:
2 left
💡 Hint
Think about what adding all numbers in the array means.
❓ Predict Output
intermediate
2:00remaining
Iterating over a dictionary with for-in
What will this Swift code print?
let dict = ["a": 1, "b": 2, "c": 3]
var keys = ""
for key in dict.keys {
    keys += key
}
print(keys)
Swift
let dict = ["a": 1, "b": 2, "c": 3]
var keys = ""
for key in dict.keys {
    keys += key
}
print(keys)
A"cba"
BAny permutation of "abc"
C"abc"
DError: Cannot iterate over dict.keys
Attempts:
2 left
💡 Hint
Dictionary keys are iterated in insertion order since Swift 5.0.
🔧 Debug
advanced
2:00remaining
Identify the error in for-in loop over a set
What error does this Swift code produce?
let fruits: Set = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit.uppercased())
}
Swift
let fruits: Set = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit.uppercased())
}
ANo error; prints uppercase fruit names in any order
BError: Cannot iterate over a Set
CRuntime error: fruit is nil
DError: 'uppercased()' is not a method on String
Attempts:
2 left
💡 Hint
Sets can be iterated like arrays.
❓ Predict Output
advanced
2:00remaining
Output of nested for-in loops with arrays
What is the output of this Swift code?
let arr1 = [1, 2]
let arr2 = ["a", "b"]
var output = ""
for num in arr1 {
    for letter in arr2 {
        output += "\(num)\(letter) "
    }
}
print(output)
Swift
let arr1 = [1, 2]
let arr2 = ["a", "b"]
var output = ""
for num in arr1 {
    for letter in arr2 {
        output += "\(num)\(letter) "
    }
}
print(output)
A"1a 1b 2a 2b "
B"a1 b1 a2 b2 "
C"1a 2a 1b 2b "
D"Error: Cannot concatenate Int and String"
Attempts:
2 left
💡 Hint
The outer loop runs first, then the inner loop fully for each outer item.
📝 Syntax
expert
2:00remaining
Which option causes a syntax error in for-in loop?
Which of these Swift for-in loops will cause a syntax error?
let items = ["x", "y", "z"]
Swift
let items = ["x", "y", "z"]
Afor item in items { print(item) }
B
for item in items {
print(item)
}
C
}
)meti(tnirp
{ smeti ni meti rof
Dfor item in items print(item)
Attempts:
2 left
💡 Hint
Swift requires braces {} for the body of for-in loops.

Practice

(1/5)
1. What does the following Swift code do?
let numbers = [1, 2, 3]
for number in numbers {
    print(number)
}
easy
A. Prints each number in the array one by one
B. Prints the entire array once
C. Causes a syntax error
D. Prints the sum of the numbers

Solution

  1. Step 1: Understand the for-in loop structure

    The loop goes through each element in the array named 'numbers'.
  2. Step 2: Observe the print statement inside the loop

    Each element is printed on its own line as the loop runs.
  3. Final Answer:

    Prints each number in the array one by one -> Option A
  4. Quick Check:

    for number in numbers prints each number [OK]
Hint: For-in loops print items one at a time [OK]
Common Mistakes:
  • Thinking it prints the whole array at once
  • Confusing the loop variable with the collection
  • Expecting a sum instead of individual prints
2. Which of the following is the correct syntax for a for-in loop iterating over an array named fruits in Swift?
easy
A. for fruit in fruits { print(fruit) }
B. for (fruit : fruits) { print(fruit) }
C. for fruit to fruits { print(fruit) }
D. foreach fruit in fruits { print(fruit) }

Solution

  1. Step 1: Recall Swift for-in loop syntax

    The correct syntax uses 'for variable in collection { }'.
  2. Step 2: Compare options to syntax

    Only for fruit in fruits { print(fruit) } matches this syntax exactly.
  3. Final Answer:

    for fruit in fruits { print(fruit) } -> Option A
  4. Quick Check:

    Correct for-in syntax uses 'in' keyword [OK]
Hint: Remember: for item in collection { } is correct [OK]
Common Mistakes:
  • Using 'to' instead of 'in'
  • Using parentheses incorrectly
  • Using 'foreach' which is not Swift syntax
3. What will be the output of this Swift code?
let names = ["Anna", "Bob", "Cara"]
for name in names {
    print(name.count)
}
medium
A. 3 3 4
B. 3 4 3
C. 4 3 3
D. 4 3 4

Solution

  1. Step 1: Identify the array elements and their lengths

    "Anna" has 4 letters, "Bob" has 3, "Cara" has 4.
  2. Step 2: Understand the loop prints each name's character count

    The loop prints 4, then 3, then 4 on separate lines.
  3. Final Answer:

    4 3 4 -> Option D
  4. Quick Check:

    name.count matches each string length [OK]
Hint: Count letters of each name inside the loop [OK]
Common Mistakes:
  • Mixing up the order of counts
  • Counting letters incorrectly
  • Assuming print outputs on same line
4. Find the error in this Swift code snippet:
let colors = ["red", "green", "blue"]
for color in colors
    print(color)
}
medium
A. Array declaration syntax is wrong
B. Variable name 'color' is invalid
C. Missing opening brace '{' after for loop
D. print statement should be outside the loop

Solution

  1. Step 1: Check for proper loop syntax

    The for-in loop requires braces '{' and '}' to enclose the loop body.
  2. Step 2: Identify missing opening brace

    The code has a closing brace '}' but no opening brace '{' after the for line.
  3. Final Answer:

    Missing opening brace '{' after for loop -> Option C
  4. Quick Check:

    for loops need braces around their body [OK]
Hint: Always use { } to wrap for loop code block [OK]
Common Mistakes:
  • Forgetting opening brace
  • Misplacing braces
  • Assuming print can be outside without braces
5. You have a dictionary of student names and their scores:
let scores = ["Alice": 85, "Bob": 92, "Cara": 78]

Using a for-in loop, how do you print only the names of students who scored above 80?
hard
A. for name in scores.keys { if scores[name] > 80 { print(name) } }
B. for (name, score) in scores { if score > 80 { print(name) } }
C. for score in scores.values { if score > 80 { print(score) } }
D. for name in scores { if scores[name] > 80 { print(name) } }

Solution

  1. Step 1: Understand dictionary iteration with key-value pairs

    Using 'for (name, score) in scores' lets you access both keys and values directly.
  2. Step 2: Apply condition to print names with score above 80

    Inside the loop, check if score > 80, then print the name.
  3. Final Answer:

    for (name, score) in scores { if score > 80 { print(name) } } -> Option B
  4. Quick Check:

    Use (key, value) pairs to filter dictionary [OK]
Hint: Use (key, value) in dictionary to access both [OK]
Common Mistakes:
  • Trying to loop only keys or values without pairing
  • Forgetting to unwrap optional values
  • Printing scores instead of names
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