Challenge - 5 Problems
Swift Loop Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a safe Swift for-in loop
What is the output of this Swift code snippet?
Swift
let numbers = [1, 2, 3, 4, 5] var sum = 0 for number in numbers { sum += number } print(sum)
Attempts:
2 left
💡 Hint
Think about what the loop does to the sum variable.
✗ Incorrect
The loop safely iterates over each element in the array and adds it to sum. The total sum of 1+2+3+4+5 is 15.
🧠 Conceptual
intermediate2:00remaining
Why Swift loops prevent out-of-bounds errors
Why do Swift loops like for-in prevent out-of-bounds errors when iterating over arrays?
Attempts:
2 left
💡 Hint
Think about how Swift protects you from common mistakes.
✗ Incorrect
Swift's for-in loop automatically iterates over valid elements only, preventing out-of-bounds access by design.
🔧 Debug
advanced2:00remaining
Identify the runtime error in this Swift loop
What error will this Swift code produce when run?
Swift
let array = [10, 20, 30] for i in 0...array.count { print(array[i]) }
Attempts:
2 left
💡 Hint
Check the range used in the loop and array indices.
✗ Incorrect
The loop uses 0...array.count which includes an index equal to array.count, causing an out-of-bounds runtime error.
📝 Syntax
advanced2:00remaining
Which Swift loop syntax is safe and correct?
Which option shows a safe and correct way to loop through an array in Swift?
Attempts:
2 left
💡 Hint
Remember Swift arrays start at index 0 and last index is count - 1.
✗ Incorrect
Option B uses a half-open range 0..
🚀 Application
expert3:00remaining
Predict the output of a nested safe Swift loop
What is the output of this Swift code?
Swift
let matrix = [[1, 2], [3, 4], [5, 6]] var total = 0 for row in matrix { for value in row { total += value } } print(total)
Attempts:
2 left
💡 Hint
Add all numbers in the nested arrays carefully.
✗ Incorrect
The nested loops safely iterate all elements in the 2D array and sum them: 1+2+3+4+5+6 = 21.