Menu
Coddy logo textTech

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 icon

Challenge

Easy

Read two lines of input:

  1. A comma-separated list of integers, the nums
  2. A comma-separated list of integers, the repeats (same length as nums)

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 ","
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow