Evaluate Bool property of optional object in if statement(在 if 语句中评估可选对象的 Bool 属性)
问题描述
当 Bool 是可选对象:
var objectWithBool: ClassWithBool?
// ...
if let obj = objectWithBool {
if obj.bool {
// bool == true
} else {
// bool == false
}
} else {
// objectWithBool == nil
}
有没有办法组合这些 if 语句?在 Objective-C 中这很容易做到,因为 nil 对象可以在同一个表达式中求值:
Is there are way to combine these if statements? In Objective-C this could easily be done, as a nil object can be evaluated in the same expression:
if (objectWithBool.bool) {
// bool == true
} else {
// bool == false || objectWithBool == nil
}
推荐答案
啊,找到了:
if objectWithBool?.bool == true {
// objectWithBool != nil && bool == true
} else {
// objectWithBool == nil || bool == false
}
可选的链接表达式objectWithBool?.bool 返回一个可选的Bool.由于它是可选的,因此 if 语句中的该表达式将根据可选是否包含值而被评估为 true/false.
The optional chaining expression objectWithBool?.bool returns an optional Bool. Since it is optional, that expression alone in the if statement would be evaluated to true/false based on whether the optional contains a value or not.
通过使用 == 运算符,if 语句检查可选项的值,在这种情况下可以是 true、false 或 nil.
By using the == operator the if statement checks the optional's value, which in this case can be true, false, or nil.
这篇关于在 if 语句中评估可选对象的 Bool 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 if 语句中评估可选对象的 Bool 属性
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- UITextView 内容插图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
