可选绑定
斯威夫特 3 & 4
var booleanValue : Bool? = false
if let booleanValue = booleanValue, booleanValue {
// Executes when booleanValue is not nil and true
// A new constant "booleanValue: Bool" is defined and set
print("bound booleanValue: '\(booleanValue)'")
}
斯威夫特 2.2
var booleanValue : Bool? = false
if let booleanValue = booleanValue where booleanValue {
// Executes when booleanValue is not nil and true
// A new constant "booleanValue: Bool" is defined and set
print("bound booleanValue: '\(booleanValue)'")
}
如果booleanValue 是nil 并且if 块不执行,则代码let booleanValue = booleanValue 返回false。如果booleanValue 不是nil,则此代码定义一个名为booleanValue 的新变量,类型为Bool(而不是可选的Bool?)。
Swift 3 和 4 代码 booleanValue(和 Swift 2.2 代码 where booleanValue)计算新的 booleanValue: Bool 变量。如果为真,if 块将使用范围内新定义的booleanValue: Bool 变量执行(允许选项在if 块内再次引用绑定值)。
注意:将绑定的常量/变量命名为与可选常量/变量相同的名称是 Swift 约定,例如 let booleanValue = booleanValue。这种技术称为可变阴影。你可以打破常规,使用let unwrappedBooleanValue = booleanValue, unwrappedBooleanValue 之类的东西。我指出这一点是为了帮助理解正在发生的事情。我建议使用可变阴影。
其他方法
零合并
对于这种特定情况,零合并很明显
var booleanValue : Bool? = false
if booleanValue ?? false {
// executes when booleanValue is true
print("optional booleanValue: '\(booleanValue)'")
}
检查false 不是很清楚
var booleanValue : Bool? = false
if !(booleanValue ?? false) {
// executes when booleanValue is false
print("optional booleanValue: '\(booleanValue)'")
}
注意:if !booleanValue ?? false 无法编译。
强制展开可选(避免)
强制解包增加了有人在未来进行更改以编译但在运行时崩溃的机会。因此,我会避免这样的事情:
var booleanValue : Bool? = false
if booleanValue != nil && booleanValue! {
// executes when booleanValue is true
print("optional booleanValue: '\(booleanValue)'")
}
一般方法
虽然这个堆栈溢出问题专门询问如何在if 语句中检查Bool? 是否为true,但确定一个通用方法是否检查真、假或将未包装的值与其他表达式组合是有帮助的.
随着表达式变得越来越复杂,我发现可选绑定方法比其他方法更灵活且更易于理解。请注意,可选绑定适用于任何可选类型(Int?、String? 等)。