LoginSignup
1
0

More than 5 years have passed since last update.

flatMapをcompactMapに置換したらerrorでた時の対処

Last updated at Posted at 2018-04-03

問題

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.
1
0
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
0