LoginSignup
51
31

More than 3 years have passed since last update.

if let b = a as? Intより if case let b as Int = a の方が速い

Last updated at Posted at 2020-10-12

Swiftにおいてキャストしてその値を使うときはas?でキャスト、
Optional型にしてそのOptional型に関する
Optional Bindingによって値を取り出すことが多いと思います。

let a: Any = 120
if let b = a as? Int {
    // b を使う処理
}

しかし、これだと一回Optionalを経由しているため流れが少し複雑です。

別の書き方があります。

let a: Any = 120
if case let b as Int = a {
    // b を使う処理
}

これだと、Optionalを通らず安全にキャストできます。

速度面

1万回実行時の速度

as? case
0.011s 0.001s

約10倍の差がある。

Swift Standart Libraryでも case の方が多用されている。

Swift.printの中身から引用

スクリーンショット 2020-10-12 18.00.15.png
https://github.com/apple/swift/blob/9af806e8fd93df3499b1811deae7729176879cb0/stdlib/public/core/OutputStream.swift#L375

51
31
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
51
31