CompactMap vs FlatMap — Swift
Map is a function in Swift that takes an array and applies a given closure (a block of code) to each element of the array, returning a new array containing the results. The closure is passed each element of the original array one at a time, and the closure's return value is used to create a new element in the resulting array.
let numbers = [1, 2, 3, 4]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // [1, 4, 9, 16]
In this example, the map
function is called on the numbers
array and it applies the closure {$0 * $0} to each element of the array and returns new array with the squared values of the original array
let stringArray = ["1", "2", "3"]
let intArray = stringArray.map { Int($0) }
print(intArray) // [1, 2, 3]
In this example, the map
function is called on the stringArray
and it applies the closure {Int($0)} to each element of the array and returns new array with the int values of the original array.
CompactMap
compactMap
is similar to map
, but it also filters out any nil
values that may be produced by the closure, and returns a new array containing the non-nil results.
let array: [Int?] = [1, nil, 2, nil, 3]
let compactedArray = array.compactMap { $0 }
print(compactedArray) // [1, 2, 3]
FlatMap
flatMap
is also similar to map
, but instead of returning an array of arrays, it returns a single array containing all of the elements from the inner arrays.
let arrayOfArrays = [[1, 2, 3], [4, 5], [6]]
let flattenedArray = arrayOfArrays.flatMap { $0 }
print(flattenedArray) // [1, 2, 3, 4, 5, 6]