Challenge - 5 Problems
Swift Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of enumerated array iteration
What is the output of this Swift code?
Swift
let fruits = ["Apple", "Banana", "Cherry"] for (index, fruit) in fruits.enumerated() { print("\(index): \(fruit)") }
Attempts:
2 left
💡 Hint
Remember that enumerated() gives pairs of (index, element) starting at 0.
✗ Incorrect
The enumerated() method returns a sequence of pairs (index, element) starting from 0. The loop prints the index and fruit separated by a colon.
❓ Predict Output
intermediate2:00remaining
Enumerated index starting value
What will be printed by this Swift code?
Swift
let numbers = [10, 20, 30] for (index, number) in numbers.enumerated() { print(index + 1, number) }
Attempts:
2 left
💡 Hint
The index from enumerated() starts at 0, but the code adds 1 before printing.
✗ Incorrect
The enumerated() method starts index at 0, but the code prints index + 1, so indexes start at 1 in output.
🔧 Debug
advanced2:00remaining
Why does this enumerated loop cause an error?
This Swift code causes a compile error. What is the reason?
Swift
let items = ["a", "b", "c"] for index, item in items.enumerated() { print(index, item) }
Attempts:
2 left
💡 Hint
Check the syntax for tuple unpacking in for loops.
✗ Incorrect
In Swift, when unpacking tuples in a for loop, parentheses are required around the variables: for (index, item) in ...
❓ Predict Output
advanced2:00remaining
Output of modifying array during enumerated iteration
What is the output of this Swift code?
Swift
var letters = ["x", "y", "z"] for (i, letter) in letters.enumerated() { letters[i] = letter.uppercased() } print(letters)
Attempts:
2 left
💡 Hint
Think about whether modifying elements by index during iteration is allowed.
✗ Incorrect
The code modifies each element by index during iteration, which is allowed. The letters become uppercase.
🧠 Conceptual
expert2:00remaining
Count of elements after filtering with enumerated
Given this Swift code, how many elements will be in the filtered array?
Swift
let values = [5, 10, 15, 20, 25] let filtered = values.enumerated().filter { index, value in index % 2 == 0 && value > 10 }.map { $0.element } print(filtered.count)
Attempts:
2 left
💡 Hint
Check which elements have even index and value greater than 10.
✗ Incorrect
Indexes 0, 2, 4 are even. Values at these indexes are 5, 15, 25. Only 15 and 25 are > 10, so 2 elements. But 5 is not > 10, so filtered elements are 15 and 25. Wait, 15 at index 2 and 25 at index 4. So count is 2.