Hint: Reduce with + sums all items starting from initial value [OK]
Common Mistakes:
Confusing reduce with map or filter output
Forgetting initial value in reduce
Expecting array output instead of single value
4. Identify the error in this Swift code snippet:
let words = ["apple", "banana", "cherry"]
let filtered = words.filter { word in
word.count > 5
}
print(filtered)
medium
A. No error, code runs correctly
B. Incorrect use of filter instead of map
C. Using word.count instead of word.length
D. Missing return keyword inside filter closure
Solution
Step 1: Check filter closure syntax
The closure uses implicit return because it is a single expression, so no explicit return is needed.
Step 2: Verify property usage
word.count is the correct way to get string length in Swift, so no error there.
Final Answer:
No error, code runs correctly -> Option A
Quick Check:
Single-expression closures return implicitly [OK]
Hint: Single-expression closures return automatically, no return needed [OK]
Common Mistakes:
Adding unnecessary return keyword
Confusing count with length property
Thinking filter needs map syntax
5. Given an array of integers, how would you use map, filter, and reduce together to find the sum of squares of only the odd numbers?
Choose the correct Swift code.
hard
A. let sum = numbers.map { $0 * $0 }.filter { $0 % 2 != 0 }.reduce(0, +)
B. let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +)
C. let sum = numbers.reduce(0) { $0 + $1 * $1 }
D. let sum = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
Solution
Step 1: Filter odd numbers first
We want only odd numbers, so use filter { $0 % 2 != 0 } to keep them.
Step 2: Map to square each odd number
Use map { $0 * $0 } to get squares of the filtered odd numbers.
Step 3: Reduce to sum all squares
Use reduce(0, +) to add all squared values into one sum.
Final Answer:
let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +) -> Option B
Quick Check:
Filter odds, map squares, reduce sum [OK]
Hint: Filter odds first, then map squares, finally reduce sum [OK]
Common Mistakes:
Mapping before filtering odd numbers
Filtering even numbers by mistake
Using reduce without mapping squares
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.