0Pricing
Swift Academy · Lesson

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. IntString)

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

  1. map and compactMap
  2. filter and Predicates
  3. reduce and reduce(into:)
  4. flatMap and Chaining
← Back to Swift Academy