swift 中的可选 if 语句在幕后发生了什么

what is happening behind the scenes in optional if statements in swift

根据 apple 文档,以下代码检查 convertedNumber 是否已初始化,如果已初始化,则执行 if 块。

let convertedNumber: Int?

if convertedNumber {
//do stuff
}

我对幕后发生的事情很感兴趣。这是某种 shorthand 表示法吗,因为 if 语句中的条件必须计算为布尔值 true 或 false。 convertedNumebr 包含的值如何转换为 true 或 false?

我认为这是 shorthand 表示法:

if convertedNumber!=nil {
//do stuff
}

如有错误请指正

可选项的"shorthand test"

if someOptional {
//do stuff
}

仅存在于 Swift 的早期版本中。 来自 Xcode 6 beta 5 发行说明:

Optionals no longer conform to the BooleanType (formerly LogicValue) protocol, so they may no longer be used in place of boolean expressions (they must be explicitly compared with v != nil). This resolves confusion around Bool? and related types, makes code more explicit about what test is expected, and is more consistent with the rest of the language.

因此对于当前 Xcode 版本,您必须使用

进行测试
if someOptional != nil {
//do stuff
}

或者,当然,使用可选的绑定。

此外,struct Optional符合NilLiteralConvertible 协议,因此(在此上下文中)nilOptional<T>.None 与匹配类型 T.