LoginSignup
20
11

More than 1 year has passed since last update.

for文でcompactMapするのはやめよう!

Posted at

Swiftでオプショナルな要素を持つ配列をfor文で回すとき、compactMapしてから回すことが多々あると思います。

↓ こういうの

let array: [Int?] 

for elm in array.compactMap({ $0 }) {
   // do something...
}

ただこれ、compactMapで余計に新しい配列を生成していて割とコストがかかっているのと、for in ...の部分でTrailing Closureが使えないので文法的にも他部分と整合性が取りにくくなります。

そこでfor case in文(造語)を使うと割と綺麗に書けます。

let array: [Int?] 

for case .some(let e) in array {
   // do something...
}

速度の比較をしてみると2倍くらい違うので積極的に使ってい行こう、というメモでした。

let array: [Int?]

let start = Date()
for _ in 0...100 {
    for e in array.compactMap({ $0 }) { ... }
}    
print(Date().timeIntervalSince(start), "s")  // 0.443s

// ----------

let start = Date()
for _ in 0...100 {
    for case .some(let e) in array { ... }
}

print(Date().timeIntervalSince(start), "s") // 0.209s

20
11
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
20
11