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

标签 swift option-type

根据 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),以便(在此上下文中)nilOptional<T>.None与匹配类型 T .

关于swift - swift 中的可选 if 语句在幕后发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28986480/

相关文章:

swift - Eureka 获取字典值 Swift

objective-c - 是什么让 Swift 的 "Optional"比 Objective-C 的 "nil"更安全?

typeclass - 如何使用 Agda 标准库的类型类实例,例如也许是适用的?

ios - fatal error : unexpectedly found nil while unwrapping an Optional Value making Custom UITableViewCell

swift - 如何使用 lookAtConstraint 获取节点的方向

ios - 在自定义 UITableViewCell 中访问 UITextField 而不创建新类?

ios - 以编程方式更改根ViewController

swift - 从 SKScene 继续并再次返回导致游戏到 "freeze"

swift - 使用 swift 的 Google Places API Web 服务返回错误 303

java - 检查流的任何元素是否不存在