Array.map() / compactMap() / flatMap()
Higher-order functions for transforming and processing each element of an array. They handle general transformation, removal of optionals, and flattening of nested arrays, respectively.
Syntax
// Returns a new array with each element transformed.
array.map { transformation }
// Returns an array with nil results excluded.
array.compactMap { transformation }
// Returns an array with the transformation results flattened into one dimension.
array.flatMap { transformation }
Method List
| Method | Description |
|---|---|
| map(_:) | Applies a closure to each element and returns a new array of the transformed values. The returned array always has the same number of elements as the original. |
| compactMap(_:) | Transforms each element and returns an array with any nil results removed. Ideal for optional-returning transformations. |
| flatMap(_:) | Transforms each element into a sequence and returns a single, flattened one-dimensional array of all the results. |
Sample Code
// map: Transform each element.
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8, 10]
let names = ["alice", "bob", "charlie"]
let upper = names.map { $0.uppercased() }
print(upper) // ["ALICE", "BOB", "CHARLIE"]
// compactMap: Remove failed conversions (nil).
let strings = ["1", "two", "3", "four", "5"]
let ints = strings.compactMap { Int($0) }
print(ints) // [1, 3, 5] (strings that cannot be converted are excluded)
// Remove nil values from an array of optionals.
let optionals: [String?] = ["apple", nil, "orange", nil, "grape"]
let fruits = optionals.compactMap { $0 }
print(fruits) // ["apple", "orange", "grape"]
// flatMap: Flatten a nested array.
let nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
let flat = nested.flatMap { $0 }
print(flat) // [1, 2, 3, 4, 5, 6, 7, 8]
// Convert strings to arrays of characters and combine them.
let words = ["swift", "code"]
let chars = words.flatMap { $0 }
print(chars) // ["s", "w", "i", "f", "t", "c", "o", "d", "e"]
Overview
map() is the most fundamental higher-order function for transforming every element of an array. The closure argument $0 represents each element, and whatever value you return becomes an element in the new array. The original array is never modified, and the result always contains the same number of elements.
compactMap() is particularly useful for type conversions (e.g., String to Int) and any transformation that returns an optional. Rather than chaining map() with filter { $0 != nil } and map { $0! }, using a single compactMap() is both safer and more concise.
For filtering array elements, see filter(). For aggregation, see reduce().
If you find any errors or copyright issues, please contact us.