120
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TIPS】今すぐ `.filter{...}.first` をやめましょう

Last updated at Posted at 2018-08-02

よくこのような構文を見かけたりするのではないでしょうか:

let array: [String] = [
    "Apple",
    "Boy",
    "Cat"
]

let target = array.filter({ $0.hasPrefix("A") }).first
// target == "Apple"

ところがこの書き方、微妙にパフォーマンスが悪い(結果見つかったとしても最後まで回る)のと、微妙に意図が読み取りづらいですね。

Swift には first(where:) というものがありますので積極的にこちらを利用しましょう:

let target = array.first(where: { $0.hasPrefix("A") })
// target == "Apple"

この書き方だと、結果見つかったらループから抜けるのでパフォーマンスが少し良くなるだけでなく、一目で「配列の中の最初の A で始まる単語を返す」ってわかるのでとてもオススメです。

ちなみにインデックスを探すときも同じような書き方でできます:

let targetIndex = array.firstIndex(where: { $0.hasPrefix("A") })
// targetIndex == 0
120
49
6

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
120
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?