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
- map and compactMap
- filter and Predicates
- reduce and reduce(into:)
- flatMap and Chaining