Nil-Coalescing 运算符
nil-coalescing 运算符 <OPTIONAL> ?? <DEFAULT VALUE> 如果包含值则展开 <OPTIONAL>,如果为 nil 则返回 <DEFAULT VALUE>。<OPTIONAL> 始终是可选类型。<DEFAULT VALUE> 必须与 <OPTIONAL> 中存储的类型相匹配。
nil-coalescing 运算符是下面使用三元运算符的代码的简写:
a != nil ? a! : b
这可以通过以下代码验证:
(a ?? b) == (a != nil ? a! : b) // ouputs true
时间示例
let defaultSpeed:String = "Slow"
var userEnteredSpeed:String? = nil
print(userEnteredSpeed ?? defaultSpeed) // ouputs "Slow"
userEnteredSpeed = "Fast"
print(userEnteredSpeed ?? defaultSpeed) // ouputs "Fast"