map and compactMap
Transform elements and drop nils.
What Is map?
map is a higher-order function: it takes a closure and applies it to every element of a sequence, returning a new array of the transformed results.
- The original collection is never mutated
- The result count always equals the input count
- The element type can change (e.g.
Int→String)
A Simple map
Doubling every number in an array:
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8]All lessons in this course
- map and compactMap
- filter and Predicates
- reduce and reduce(into:)
- flatMap and Chaining