Swift Collections 型のAPIについて

  • 2021-02-07
  • 2021-02-07
  • Swift
  • 897View
  • 0件

map

Returns an array containing the results of mapping the given closure over the sequence’s elements.

mapは配列の全要素に対して渡したクロージャを実行して配列を返します
let nums = [1, 2, 3, 4, 5]
let doubleNums = nums.map { $0 * 2 }
print(doubleNums) // [2, 4, 6, 8, 10]

compactMap

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
compactMapはmapと異なる点は Optionalではない 配列を返します
let strNums = ["1", "2", "hoge", "4", "5"]
let nums = strNums.map { Int($0) }
print(nums) // [Optional(1), Optional(2), nil, Optional(4), Optional(5)]
// map の場合はnilを含み、OptionalなInt型となっている

// compactMapの場合、配列にはnilを含まず、要素はInt型を返しています
let nums = strNums.compactMap { Int($0) }
print(nums) // [1, 2, 4, 5]

flatMap

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence. In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()).
flatMapはmapの結果に対して全要素をjoinedで連結させます
let numbers = [1, 2, 3, 4]

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

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
最新情報をチェックしよう!