在 if 语句中评估可选对象的 Bool 属性

2023-10-05移动开发问题
9

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

The End

相关推荐

无法将文件从捆绑包复制到 iOS 中的文档目录
Can`t copy file from bundle to documents directory in iOS(无法将文件从捆绑包复制到 iOS 中的文档目录)...
2024-04-15 移动开发问题
4

如何复制“字典"在斯威夫特?
How to copy a quot;Dictionaryquot; in Swift?(如何复制“字典在斯威夫特?)...
2024-04-15 移动开发问题
10

Swift - 迭代结构对象时如何对其进行变异
Swift - How to mutate a struct object when iterating over it(Swift - 迭代结构对象时如何对其进行变异)...
2024-04-15 移动开发问题
7

如何使用 Swift 将文本复制到剪贴板/粘贴板
How to copy text to clipboard/pasteboard with Swift(如何使用 Swift 将文本复制到剪贴板/粘贴板)...
2024-04-15 移动开发问题
9

Swift 无法使用类型为“([Score],Score)"的参数列表调用“find",其中 Sco
Swift Cannot invoke #39;find#39; with an argument list of type #39;([Score], Score)#39; where Score is a struct(Swift 无法使用类型为“([Score],Score)的参数列表调用“find,其中 Score 是一个结构)...
2024-04-15 移动开发问题
6

如何使用 UIImageViewExtension 与 Swift 异步加载图像并防止重复图像或错误图像加载到单元格
How to load image asynchronously with Swift using UIImageViewExtension and preventing duplicate images or wrong Images loaded to cells(如何使用 UIImageViewExtension 与 Swift 异步加载图像并防止重复图像或错误图像加载到单元格) - IT屋-程序员软...
2024-04-15 移动开发问题
3