SwiftMidMCQ
What is the difference between `map`, `flatMap`, and `compactMap`?
Test your knowledge:
Explanation & Code
Answer: All three transform collections but handle the results differently.
| Function | Use case |
|---|---|
map | Transform each element, keep all results |
compactMap | Transform and remove nil results |
flatMap | Transform and flatten nested collections |
Code Example:
let numbers = [1, 2, 3, 4]
// map — transforms every element
let doubled = numbers.map { $0 * 2 }
// [2, 4, 6, 8]
// compactMap — removes nils
let strings = ["1", "two", "3", "four"]
let integers = strings.compactMap { Int($0) }
// [1, 3]
// flatMap — flattens nested arrays
let nested = [[1, 2], [3, 4], [5, 6]]
let flat = nested.flatMap { $0 }
// [1, 2, 3, 4, 5, 6]
Rate your understanding: