在 none 可选变量上应用 Nil-Coalescing 运算符时不会触发任何错误
It does not trigger any errors when apply the Nil-Coalescing operator on a none optional variable
The nil-coalescing operator (a ?? b) unwraps an optianl a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type.
The Nil-Coalescing operator is shorthand for the code below
a != nil ? a! : b
然后我尝试了以下测试代码片段
//First
let a: Int = 3, b: Int = 4
a ?? b // No error
&
//Second
let a: Int = 3, b: Int = 4
a != nil ? a! : b //Triggers an error: value of type 'int' can never be nil, comparison isn't allowed
问题:
为什么编译器没有为第一个代码片段报错而为第二个代码片段大喊错误?他们不一样吗?
非常感谢
nil 合并运算符
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T
将可选作为第一个操作数。所以 a ?? b
和 a != nil ? a! : b
是等效的,前提是 a
是可选的。
你的例子不是这种情况
let a: Int = 3, b: Int = 4
a ?? b
第一个操作数 a
不是可选的。但是,编译器可以
"wrap" 一个非可选的值 T
变成一个可选的 T?
顺序
匹配函数或运算符。例如,在
func foo(x: Int?) { }
foo(3)
参数 3
被包装成 Int?
。
在你的例子中,表达式等同于
Optional<Int>.Some(a) ?? b
相当于
Optional<Int>.Some(a) != nil ? Optional<Int>.Some(a)! : b
然而,编译器并没有那么聪明地认识到
Optional<Int>.Some(a)
不能是 nil
.
The nil-coalescing operator (a ?? b) unwraps an optianl a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type.
The Nil-Coalescing operator is shorthand for the code below
a != nil ? a! : b
然后我尝试了以下测试代码片段
//First
let a: Int = 3, b: Int = 4
a ?? b // No error
&
//Second
let a: Int = 3, b: Int = 4
a != nil ? a! : b //Triggers an error: value of type 'int' can never be nil, comparison isn't allowed
问题:
为什么编译器没有为第一个代码片段报错而为第二个代码片段大喊错误?他们不一样吗?
非常感谢
nil 合并运算符
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T
将可选作为第一个操作数。所以 a ?? b
和 a != nil ? a! : b
是等效的,前提是 a
是可选的。
你的例子不是这种情况
let a: Int = 3, b: Int = 4
a ?? b
第一个操作数 a
不是可选的。但是,编译器可以
"wrap" 一个非可选的值 T
变成一个可选的 T?
顺序
匹配函数或运算符。例如,在
func foo(x: Int?) { }
foo(3)
参数 3
被包装成 Int?
。
在你的例子中,表达式等同于
Optional<Int>.Some(a) ?? b
相当于
Optional<Int>.Some(a) != nil ? Optional<Int>.Some(a)! : b
然而,编译器并没有那么聪明地认识到
Optional<Int>.Some(a)
不能是 nil
.