Challenge - 5 Problems
Swift For-in Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Think about what adding all numbers in the array means.
✗ Incorrect
The for-in loop goes through each number and adds it to result. 1+2+3+4 equals 10.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Dictionary keys are iterated in insertion order since Swift 5.0.
✗ Incorrect
Since Swift 5.0, the keys property returns a collection of keys in insertion order. For this dictionary, the output is "abc".
🔧 Debug
advanced2: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()) }
Attempts:
2 left
💡 Hint
Sets can be iterated like arrays.
✗ Incorrect
Sets in Swift conform to Sequence, so you can use for-in loops. Strings have the uppercased() method. The output order is not guaranteed.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The outer loop runs first, then the inner loop fully for each outer item.
✗ Incorrect
The outer loop goes through 1 and 2. For each, the inner loop goes through "a" and "b". So output is "1a 1b 2a 2b ".
📝 Syntax
expert2: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"]
Attempts:
2 left
💡 Hint
Swift requires braces {} for the body of for-in loops.
✗ Incorrect
Option D misses braces and does not allow omitting them for multi-line statements, causing a syntax error.