问题描述
当 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 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)