swift - 如何评估连续的 if 语句?

标签 swift swift4

我有两个 if 语句要检查,其中一个检查的成本非常高。所以我想知道以下哪个语句的性能最高:

1) 我不喜欢“厄运金字塔”,但我确信它工作正常

for customObject in array {
    if customObject.isSimpleBool {
        if customObject.isCostlyBool {
            // do some stuff
        }
    }
}

2) 我通常是这样写的……但是如果 isSimpleBoolfalse,它会检查 isCoSTLyBool 吗?

for customObject in array {
    if customObject.isSimpleBool && customObject.isCostlyBool {
        // do some stuff
    }
}

3) 我知道这行得通,但它的评估方式是否与解决方案 2 不同?

for customObject in array {
    if customObject.isSimpleBool, customObject.isCostlyBool {
        // do some stuff
    }
}

4) 是否还有其他我没有找到的解决方案?

最佳答案

for customObject in array {
    if customObject.isSimpleBool && customObject.isCostlyBool {
        // do some stuff
    }
}

这行得通,我已经多次使用这些带有 nil 检查的语句。

if (obj != nil && obj!.property == false) {}

obj 为 nil 的情况下,永远不会调用 obj.property(否则应用程序会崩溃)

关于swift - 如何评估连续的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44723537/

相关文章:

ios - ReactiveSwift 中运算符 '<~' 的使用不明确

ios - Xcode 6.4 Playground CPU 使用率极高

ios - 自定义 xib 在 super View 中大小不正确

arrays - swift3 在​​侧闭包中获取数组

swift - 如何覆盖 Swift 中的属性?

swift - request.allHTTPHeaderFields 总是返回 Optional([ :])

ios - 滚动时收集 View 可重复使用的单元格问题

ios - 我可以在单击按钮时以编程方式更改 Localizable.strings 文件而不重新启动应用程序吗

ios - 在绘图应用程序 Swift 3 中使用 UndoManager 实现重做和撤消

swift - cccrypt 在 swift 4 中生成奇怪的输出