if case let b as Int = a is faster than if let b = a as? Int

When casting in Swift and using that value, cast with ʻas?, Make it a ʻOptional type and relate to that ʻOptional type I think you often retrieve the value with ʻOptional Binding.

let a: Any = 120
if let b = a as? Int {
    //Processing using b
}

However, in this case, the flow is a little complicated because it goes through ʻOptional` once.

There is another way to write it.

let a: Any = 120
if case let b as Int = a {
    //Processing using b
}

With this, you can safely cast without going through Optional.

Speed surface

Speed when running 10,000 times

as? case
0.011s 0.001s

There is a difference of about 10 times.

The Swift Standart Library also uses case more often.

Quoted from the contents of Swift.print

![Screenshot 2020-10-12 18.00.15.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/117659/d90e5b26-0aa2-42af-f6f4 -6bd5ff9d8025.png) https://github.com/apple/swift/blob/9af806e8fd93df3499b1811deae7729176879cb0/stdlib/public/core/OutputStream.swift#L375

Recommended Posts

if case let b as Int = a is faster than if let b = a as? Int
Resultset's next () was misunderstood as a method to determine if there is a next