mapの挙動
配列の全ての要素を参照して新しい配列を返す.
let intNumberList: [Int] = [1, 2, 3, 4, 5]
let stringNumberList: [String] = intNumberList.map { "\($0)" }
print(stringNumberList) // ["1", "2", "3", "4", "5"]
compactMapの挙動
nil以外の要素を参照して新しい配列を返す.
let optionalStringNumberList: [Int?] = [1, 2, nil, 4, 5]
let intNumberList: [Int] = optionalStringNumberList.compactMap { $0 }
print(intNumberList) // [1, 2, 4, 5]
flatMapの挙動
多次元配列を参照し, 一次元配列に変換する.
let intNumberList: [[Int]] = [[1, 2, 3], [1, 2, 3]]
let intNumberListWithFlatMap: [Int] = intNumberList.flatMap { $0 }
print(intNumberListWithFlatMap) // [1, 2, 3, 1, 2, 3]
併用
flatMapとmapを併用できる.
let intNumberList: [[Int]] = [[1, 2, 3], [1, 2, 3]]
let stringNumberListWithFlatMap: [String] = intNumberList.flatMap { $0.map { "\($0)" }
print(stringNumberListWithFlatMap) // ["1", "2", "3", "1", "2", "3"]