0
0
Swiftprogramming~20 mins

Map, filter, reduce patterns in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MapFilterReduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1, 2, 3, 4, 5]
B[2, 4]
C[6, 8, 10]
D[10]
Attempts:
2 left
💡 Hint
First multiply each number by 2, then keep only those greater than 5.
Predict Output
intermediate
2: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)
A21
B12
C0
D6
Attempts:
2 left
💡 Hint
Filter even numbers, then add them all together.
🔧 Debug
advanced
2: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)
ARuntime error: index out of range
BMissing initial result in reduce causes a compile error
CType mismatch error
DNo error, prints "apple, banana, cherry"
Attempts:
2 left
💡 Hint
Reduce without an initial value uses the first element as the initial accumulator if the array is non-empty.
Predict Output
advanced
2: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)
A8
B24
C6
D1
Attempts:
2 left
💡 Hint
Divide each by 3, keep even numbers, then multiply all starting from 1.
🧠 Conceptual
expert
2: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 }
A−2
B−18
C12
D10
Attempts:
2 left
💡 Hint
Start from 10, subtract each element in order.