Swiftly

Swift 5.7 references for busy coders

flatMap

flatMap is a functional method that returns an array that contains the results of mapping a given closure over the elements of a sequence, with the exception that if the results are arrays, they are concatenated to one array. Similar methods are map and compactMap.

flatMap over array of Ints

let numbers = [1, 2, 3, 4]
let eachNumber3Times = numbers.flatMap { Array(repeating: $0, count: 3) }
print(eachNumber3Times) // [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

For reference, here is what would happen if we used map with this example instead:

let numbers = [1, 2, 3, 4]
let eachNumber3Times = numbers.map { Array(repeating: $0, count: 3) }
print(eachNumber3Times) // [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]