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 属性
基础教程推荐
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
