0Pricing
Swift Academy · Lesson

flatMap and Chaining

Flatten nested collections and chain transforms.

Two Faces of flatMap

flatMap on a sequence flattens one level of nesting. It applies a closure that returns a sequence for each element, then concatenates all those sequences into one flat array.

Flattening Nested Arrays

Turn an array of arrays into a single array:

let nested = [[1, 2], [3, 4], [5]]
let flat = nested.flatMap { $0 }
print(flat)  // [1, 2, 3, 4, 5]

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