在阅读官方 Apple 指南时我发现了这个
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello \(name)"
}
有一个常量声明和赋值,其中我 — 作为初学者 — 期望表达式返回 boolean
。但这个的条件if
声明似乎得到true
作为值,因为正在执行括号内的代码。
常量的初始化是否返回 boolean
值或 if
的东西语句可以用作条件吗?
最佳答案
这称为可选绑定(bind)。引用基础知识 -> Optionals -> Swift 语言指南的可选绑定(bind)部分。
You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.
这个if let
构造的作用是检查someOptional
是否存在。如果它不是 nil
/.None
那么它会将可选值“绑定(bind)”到常量。
if let constantName = someOptional {
...
}
这可以被认为是:
if someOptional != nil {
let constantName = someOptional!
....
}
关于swift - 为什么我可以使用常量初始化作为 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35046489/