0
0
Swiftprogramming~5 mins

FlatMap for nested collections in Swift

Choose your learning style9 modes available
Introduction

FlatMap helps you turn a list of lists into a single list. It makes nested collections easier to work with by flattening them.

You have an array of arrays and want one simple array with all items.
You want to remove empty or nil values while flattening nested collections.
You want to combine multiple lists into one without extra loops.
Syntax
Swift
let flatArray = nestedArray.flatMap { $0 }

The closure { $0 } means take each inner array as it is.

flatMap flattens one level of nesting in the collection.

Examples
This turns [[1, 2], [3, 4], [5]] into [1, 2, 3, 4, 5].
Swift
let nested = [[1, 2], [3, 4], [5]]
let flat = nested.flatMap { $0 }
print(flat)
Empty inner arrays are ignored, result is ["a", "b", "c"].
Swift
let nested = [["a", "b"], [], ["c"]]
let flat = nested.flatMap { $0 }
print(flat)
This removes nil values and flattens to [1, 3, 4].
Swift
let nested: [[Int?]] = [[1, nil], [3, 4], [nil]]
let flat = nested.flatMap { $0.compactMap { $0 } }
print(flat)
Sample Program

This program takes a nested array of numbers and flattens it into one array. Then it prints the result.

Swift
import Foundation

let nestedNumbers = [[10, 20], [30, 40, 50], [60]]

// Flatten the nested array into a single array
let flatNumbers = nestedNumbers.flatMap { $0 }

print("Flat array:", flatNumbers)
OutputSuccess
Important Notes

flatMap only flattens one level of nesting.

Use compactMap inside flatMap to remove nil values from nested optionals.

Summary

flatMap turns nested collections into a single collection.

It helps simplify working with arrays of arrays.

Use it to flatten and optionally filter nested data.