LoginSignup
1
1

map, compactMap, flatMapについて

Last updated at Posted at 2024-04-11

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"]

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1