例如,像:
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的情况下,有更好的方法吗?
由于
答案 0 :(得分:1)
首先,你应该避免强制解包并替换
if screen != nil {
// ... add predicate for `screen!` ...
}
通过可选的绑定:
if let screenValue = screen {
// ... add predicate for `screenValue` ...
}
比较When should I compare an optional value to nil?以获得该主题的详细概述。
使用map()
方法可以更紧凑地实现相同的目的
Optional
:
screen.map { /* ... add predicate for `$0` ... }
仅在screen != nil
,然后在$0
内部调用闭包
封闭是未包装的价值。
其次,用所有必需的谓词填充数组更简单 首先,只创建一次复合谓词。 这也允许您检查是否设置了任何搜索属性。
您的代码将变为
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 = %@", $0)) }
feature.map { predicates.append(NSPredicate(format: "feature = %@", $0)) }
// ... other search attributes ...
if !predicates.isEmpty {
let finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:predicates)
}