Swift 可选绑定(bind),为什么需要本地变量?

标签 swift optional-binding

我正在阅读关于 Optional Binding 的 Apple 开发人员文档

为什么我不能使用:

if someOptional? {

statements

代替

if let constantName = someOptional {

statements

为什么不需要局部变量或常量?

最佳答案

Why can't I use: if someOptional? {...}

因为可选变量上的 ? 后缀是为 optional chaining 保留的,它允许您访问属性或调用给定可选变量的方法。例如:

// returns an optional version of a given property
let aProperty = anOptional?.someProperty

// calls the method if aProperty contains a value – otherwise doesn't
aProperty?.doSomething()

如果你只想检查一个可选值是否包含一个值,而不关心那个底层值,你可以简单地将它与 nil 进行比较。例如:

if anOptional != nil {
    // do something
}

关于Swift 可选绑定(bind),为什么需要本地变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36989242/

相关文章:

swift - 可选绑定(bind)的命名约定

java - 子模块的故障安全注入(inject)器。 google guice 中的可选绑定(bind)

swift:安全访问 SCNNode 数组的字典

Swift:将协议(protocol)变量实现为惰性变量?

ios - 使用 Swift 实现 UITextFieldDelegate

ios - 使用 Swift 从 firebase 获取自定义单元类中的数据

swift - 使用 NSPredicate 将启用用户添加到 'Favourite' 对象,然后该对象将出现在单独的 TableView 中(没有 CoreData!)

ios - 移除 ViewController 消失时的键盘通知

swift - 可选绑定(bind),这里的 "Binding"这个词到底是什么意思?