flatMap
Part of the Logic & Flow section of Coddy's Swift journey — lesson 29 of 56.
flatMap is for the case where each element produces several results. The closure returns an array; flatMap concatenates all of them into one flat array.
let groups = [[1, 2, 3], [4, 5], [6]]
let all = groups.flatMap { $0 }
print(all) // [1, 2, 3, 4, 5, 6]You can do real work inside the closure too. Mapping each value to a small array and flattening the result in one step is the typical use case:
let nums = [1, 2, 3]
let pairs = nums.flatMap { [$0, $0 * $0] }
print(pairs) // [1, 1, 2, 4, 3, 9]Compare with map: that would have produced a [[Int]], an array of small arrays, which you'd need another step to flatten. flatMap rolls those two steps into one.
Challenge
EasyRead two lines of input:
- A comma-separated list of integers, the
nums - A comma-separated list of integers, the
repeats(same length asnums)
For each i, repeat nums[i] exactly repeats[i] times. Print the resulting flat array, joined with ,. Use flatMap.
For input 5,7,2 on line 1 and 3,1,2 on line 2, the output is 5,5,5,7,2,2.
Cheat sheet
flatMap maps each element to an array and concatenates all results into a single flat array:
let nums = [1, 2, 3]
let pairs = nums.flatMap { [$0, $0 * $0] }
print(pairs) // [1, 1, 2, 4, 3, 9]Unlike map (which would produce [[Int]]), flatMap flattens in one step. It can also flatten nested arrays directly:
let groups = [[1, 2, 3], [4, 5], [6]]
let all = groups.flatMap { $0 }
print(all) // [1, 2, 3, 4, 5, 6]Try it yourself
let nums = readLine()!.components(separatedBy: ",").map { Int($0)! }
let repeats = readLine()!.components(separatedBy: ",").map { Int($0)! }
// TODO: flatMap each (num, repeat) into Array(repeating:count:); join with ","
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check