我正在阅读关于 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/