在 if 语句中评估可选对象的 Bool 属性 [英] Evaluate Bool property of optional object in if statement

查看:31
本文介绍了在 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 语句检查可选项的值,在这种情况下可以是 truefalsenil.

By using the == operator the if statement checks the optional's value, which in this case can be true, false, or nil.

这篇关于在 if 语句中评估可选对象的 Bool 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆