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.

FunctionUse case
mapTransform each element, keep all results
compactMapTransform and remove nil results
flatMapTransform 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:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.