根据 apple 文档,以下代码检查 convertedNumber 是否已初始化,如果已初始化,则执行 if block 。
let convertedNumber: Int?
if convertedNumber {
//do stuff
}
我对幕后发生的事情很感兴趣。这是某种速记符号吗,因为 if 语句中的条件必须评估为 bool 值 true 或 false。 convertedNumebr 包含的值如何转换为 true 或 false?
我在想这是一个速记符号:
if convertedNumber!=nil {
//do stuff
}
如果我错了请纠正我。
最佳答案
可选值的“速记测试”
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
}
或者,当然,使用可选的绑定(bind)。
此外,struct Optional
符合 NilLiteralConvertible
协议(protocol),以便(在此上下文中)nil
与
Optional<T>.None
与匹配类型 T
.
关于swift - swift 中的可选 if 语句在幕后发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28986480/