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 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
 https://github.com/apple/swift/blob/9af806e8fd93df3499b1811deae7729176879cb0/stdlib/public/core/OutputStream.swift#L375