如何组合多个可为空的 NSPredicate?

How to combine multiple nullable NSPredicates?

例如:

    var finalPredicate = NSPredicate(format: "")

    if (screen != nil) {
        screenPredicate = NSPredicate(format: "screen = %@", screen!)
        finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [screenPredicate!])
    }

    if (feature != nil) {
        featurePredicate = NSPredicate(format: "feature = %@", feature!)
        finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [finalPredicate, featurePredicate!])
    }

    if (shouldDisplayPredicate != nil) {
        shouldDisplayPredicate = NSPredicate(format: "shouldDisplay = %@", shouldDisplay!)
        finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [finalPredicate, shouldDisplayPredicate!])
    }
    if (hasDisplayed != nil) {
        displayPredicate = NSPredicate(format: "hasDisplayed = %@", hasDisplayed!)
        finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [finalPredicate, displayPredicate!])
    }

在谓词可以为 null 或不为 null 的情况下,是否有更好的方法来做到这一点?

谢谢

首先,你应该避免强制展开并替换

if screen != nil {
    // ... add predicate for `screen!` ...
}

通过可选绑定:

if let screenValue = screen {
    // ... add predicate for `screenValue` ...
}

比较 以获得对该主题的良好概述。 使用 map() 方法可以更紧凑地实现相同的目的 的 Optional

screen.map { /* ... add predicate for `[=12=]` ... }

只有在screen != nil时才会调用闭包,然后在[=18=]里面 闭包是展开的值。

其次,用所有需要的谓词填充数组更简单 首先,只创建一次复合谓词。 这也允许您检查是否设置了任何搜索属性。

您的代码将变为

var predicates: [NSPredicate] = []
if let screenValue = screen {
    predicates.append(NSPredicate(format: "screen = %@", screenValue))
}
if let featureValue = feature {
    predicates.append(NSPredicate(format: "feature = %@", featureValue))
}
// ... other search attributes ...
if !predicates.isEmpty {
    let finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:predicates)
}

var predicates: [NSPredicate] = []
screen.map { predicates.append(NSPredicate(format: "screen = %@", [=14=])) }
feature.map { predicates.append(NSPredicate(format: "feature = %@", [=14=])) }
// ... other search attributes ...
if !predicates.isEmpty {
    let finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:predicates)
}