LoginSignup
27

More than 3 years have passed since last update.

[Swift] forとifを入れ子にするよりfor whereを使おう

Posted at

随分前からある構文ですが、私は最近気づいたので改めて書きます。
Swiftを書いていると時折こういうコードを書く必要が出てきます。

var count = 0
for i in 0..<n{
    if condition(i){
        count += 1
    }
}

forの直下にifがあり、かつelseがない場合です。

でもwhereを使えばこう書けます。

var count = 0
for i in 0..<n where condition(i){
    count += 1
}

意味は簡単で、where節が条件を指定しています。こう書くことでネストが1つ減るだけでなく、考えている条件もわかりやすくなります。
最適化のおかげでパフォーマンス上の影響は全くないので、積極的に使っていくべきだと思います。

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
27