是什么 ??操作员?
What is the ?? operator?
什么是??运算符
Swift 编程语言 (Swift 4.1)
我正在阅读 apple 的 Swift 编程语言 (Swift 4.1) 一书,我读到了其中谈到 ??运算符:
专家
Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.
摘自:Apple Inc.“Swift 编程语言 (Swift 4.1)。”电子书。 https://itunes.apple.com/us/book/the-swift-programming-language-swift-4-1/id881256329?mt=11
问题
可选值
专家里面说的是??运算符用于可选值我想知道它对可选值有什么作用。
它的作用
所以我想知道的另一件事是 ??运算符做。
Nil-Coalescing Operator (??)
零合并运算符 (a ?? b
) 解包一个可选的 a 如果它包含一个值,或者 returns 一个默认值 b
如果 a
是 nil
。表达式 a 始终是可选类型。表达式 b 必须与存储在 a
.
中的类型相匹配
?? - 表示默认值分配,当您的变量具有 nil 值时。
考虑以下示例:
var int a = nil // var a with nil value assignment
var int b = a ?? 1 // first trying to get value from a. If var a has nil then it will try assign value 1.
print("b = \(b)")
result: b = 1
什么是??运算符
Swift 编程语言 (Swift 4.1)
我正在阅读 apple 的 Swift 编程语言 (Swift 4.1) 一书,我读到了其中谈到 ??运算符:
专家
Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.
摘自:Apple Inc.“Swift 编程语言 (Swift 4.1)。”电子书。 https://itunes.apple.com/us/book/the-swift-programming-language-swift-4-1/id881256329?mt=11
问题
可选值
专家里面说的是??运算符用于可选值我想知道它对可选值有什么作用。
它的作用
所以我想知道的另一件事是 ??运算符做。
Nil-Coalescing Operator (??)
零合并运算符 (a ?? b
) 解包一个可选的 a 如果它包含一个值,或者 returns 一个默认值 b
如果 a
是 nil
。表达式 a 始终是可选类型。表达式 b 必须与存储在 a
.
?? - 表示默认值分配,当您的变量具有 nil 值时。
考虑以下示例:
var int a = nil // var a with nil value assignment
var int b = a ?? 1 // first trying to get value from a. If var a has nil then it will try assign value 1.
print("b = \(b)")
result: b = 1