After reading of the article about swift compiling time. I am interested in why usage of more than 2 sequence coalescing operator increase compilation time significantly.
Example: Compilation time 3.65 sec.
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
return 999 + (a ?? 0) + (b ?? 0) + (c ?? 0)
}
Compilation time 0.09 sec.
func fn() -> Int {
let a: Int? = nil
let b: Int? = nil
let c: Int? = nil
var res: Int = 999
if let a = a {
res += a
}
if let b = b {
res += b
}
if let c = c {
res += c
}
return res
}
Swift's nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty. Because name is an optional string, we need to unwrap it safely to ensure it has a meaningful value.
The nil-coalescing and ternary conditional operators are what's known as syntatic sugar. They sugar-coat verbose code in more concise code, and make your Swift code more readable.
I'm almost certain that this has to do with type inference. When interpreting all of those +
and ??
operators the compiler is doing a lot of work behind the scenes to infer the types of those arguments. There are around thirty overloads for the +
operator alone and when you chain several of them together you are making the compiler's job much more complicated than you might think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With