問題
flatMapを安易にcompactMap置換したら一部処理が通らない
原因
struct Ints {
let value: [Int]
}
let i = [Ints(value: [0]) ,Ints(value: [1])]
i.flatMap{ $0.value } //[0, 1]
i.compactMap{ $0.value } //[[0], [1]]
↑の例えだと
flatMapだと[Int]
で返って来るが
compactMapだと[[Int]]
で返って来るのでbuild通らなくなった
compactMap内で返す値の型が[Any]?
か[Any]
によって返って来る値が変わるらしい
[Any]?
ならflatMapが正しいのですが
[Any]
のものを取り出すのにflatMap使わなくていいじゃんって話なんですが。。。
↑修正しました
今回の使い方だとSwift4.1以降でのflatMapの使い方として問題ないので flatMapのままで良かった
ただflatMapを使うことによってwarnigが取れないのしゃあないのかな!?
対応
色々やり方はあると思いますが
一行で書くならreduceでとる
i.reduce(into: [Int]()) { $0 = $0 + $1.value }
@lovee さんから指摘頂き修正
↑の例でのflatMapの使い方でも問題はない
以下Swift4.1以降での使い方
-
compactMap
- nilを含む要素を取り出す(フィルタリング)
Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
-
flatMap
- 要素内の要素を取り出す
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.