Swift Foundation 的这个 PR 增加了 Predicate 的复合功能,如下所示:如果你的目标版本仅为这些版本及以上,则应使用此功能。
let notTooShort = #Predicate<Book> { $0.pages > 50 }
let notTooLong = #Predicate<Book> { $0.pages <= 350 }
let titleFilter = #Predicate<Book> { $0.title.contains("Swift") }
let filter = #Predicate<Book> {
(notTooShort.evaluate($0) && notTooLong.evaluate($0)) || titleFilter.evaluate($0)
}
CompoundPredicate 旨在改进 Predicate 系统,以便在构造多个谓词后能够组合它们。
let notTooShort = #Predicate<Book> {
$0.pages > 50
}
let notTooLong = #Predicate<Book> {
$0.pages <= 350
}
let lengthFilter = [notTooShort, notTooShort].conjunction()
// Match Books that are just the right length
let titleFilter = #Predicate<Book> {
$0.title.contains("Swift")
}
// Match Books that contain "Swift" in the title or
// are just the right length
let filter = [lengthFilter, titleFilter].disjunction()
文档可在此处获得:here,并且您可以像 Docc 归档一样使用 Xcode 查看。
请随时创建 Issue,或者更好的是,通过创建 pull request 积极贡献。
算术运算 (+, -, *, /, %)
+, -, * PredicateExpressions.Arithmetic/ PredicateExpressions.FloatDivision/ PredicateExpressions.IntDivision% PredicateExpressions.IntRemainder一元负号 - PredicateExpressions.UnaryMinus
范围 (..., ..<)
... PredicateExpressions.ClosedRange..< PredicateExpressions.Rangex..<z).contains(y) PredicateExpressions.RangeExpressionContains比较运算 (<, <=, >, >=, ==, !=)
<, <=, >, >= PredicateExpressions.Comparison== PredicateExpressions.Equal!= PredicateExpressions.NotEqual条件 & 三元 (?:) PredicateExpressions.Conditional
布尔逻辑 (&&, ||, !)
&& PredicateExpressions.Conjunction|| PredicateExpressions.Disjunction! PredicateExpressions.NegationSwift 可选值 (?, ??, !, flatMap(_:), if-let 表达式)
?, flatMap(_:) PredicateExpressions.OptionalFlatMap??, if-let PredicateExpressions.NilCoalesce类型 (as, as?, as!, is)
as? PredicateExpressions.ConditionalCastas, as! PredicateExpressions.ForceCast序列操作 (allSatisfy(), filter(), contains(), contains(where:), starts(with:), max(), min())
allSatisfy() PredicateExpressions.SequenceAllSatisfyfilter() PredicateExpressions.Filter [completion:: 2024-03-10]contains() PredicateExpressions.SequenceContains [completion:: 2024-03-10]contains(where:) PredicateExpressions.SequenceContainsWherestarts(with:) PredicateExpressions.SequenceStartsWithmin() PredicateExpressions.SequenceMinimum [completion:: 2024-03-10]max() PredicateExpressions.SequenceMaximum下标和成员访问 ([], .)
[0,1][0] PredicateExpressions.CollectionIndexSubscript["a": "b"]["a"] PredicateExpressions.DictionaryKeySubscript["a": "b"]["a", defaultValue: "b"] PredicateExpressions.DictionaryKeyDefaultValueSubscriptobj.someKey PredicateExpressions.KeyPath字符串比较
contains(_:) PredicateExpressions.CollectionContainsCollectionlocalizedStandardContains(_:) PredicateExpressions.StringLocalizedStandardContainscaseInsensitiveCompare(_:) PredicateExpressions.StringCaseInsensitiveComparelocalizedCompare(_:) PredicateExpressions.StringLocalizedCompare