Challenge - 5 Problems
MapFilterReduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of map and filter combination
What is the output of the following Swift code?
Swift
let numbers = [1, 2, 3, 4, 5] let result = numbers.map { $0 * 2 }.filter { $0 > 5 } print(result)
Attempts:
2 left
💡 Hint
First multiply each number by 2, then keep only those greater than 5.
✗ Incorrect
The map doubles each number: [2, 4, 6, 8, 10]. The filter keeps numbers > 5: [6, 8, 10].
❓ Predict Output
intermediate2:00remaining
Reduce to sum even numbers
What is the output of this Swift code?
Swift
let numbers = [1, 2, 3, 4, 5, 6] let sumEven = numbers.filter { $0 % 2 == 0 }.reduce(0) { $0 + $1 } print(sumEven)
Attempts:
2 left
💡 Hint
Filter even numbers, then add them all together.
✗ Incorrect
Even numbers are [2, 4, 6]. Their sum is 2 + 4 + 6 = 12.
🔧 Debug
advanced2:00remaining
Identify the error in reduce usage
What error does this Swift code produce?
Swift
let words = ["apple", "banana", "cherry"] let sentence = words.reduce { $0 + ", " + $1 } print(sentence)
Attempts:
2 left
💡 Hint
Reduce without an initial value uses the first element as the initial accumulator if the array is non-empty.
✗ Incorrect
No error. Swift's `reduce` without an initial value uses the first element ("apple") as the starting accumulator and applies the closure to combine with subsequent elements: "apple, banana" then "apple, banana, cherry".
❓ Predict Output
advanced2:00remaining
Chained map, filter, reduce output
What is the output of this Swift code?
Swift
let values = [3, 6, 9, 12] let result = values.map { $0 / 3 }.filter { $0 % 2 == 0 }.reduce(1) { $0 * $1 } print(result)
Attempts:
2 left
💡 Hint
Divide each by 3, keep even numbers, then multiply all starting from 1.
✗ Incorrect
Map: [1, 2, 3, 4]. Filter even: [2, 4]. Reduce multiply: 1 * 2 * 4 = 8.
🧠 Conceptual
expert2:00remaining
Understanding reduce initial value impact
Given the array [2, 4, 6], what is the value of 'result' after running this Swift code?
let result = [2, 4, 6].reduce(10) { acc, val in acc - val }
Attempts:
2 left
💡 Hint
Start from 10, subtract each element in order.
✗ Incorrect
Calculation: 10 - 2 = 8; 8 - 4 = 4; 4 - 6 = -2.