它正在使用:
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
来源:RealmCollectiton
在引擎盖下,它正在使用NSPredicate(format:)
,它通过简化和避免每次写入来“隐藏”它NSPredicate(format: ...)
,并且也应该使用 KeyPath。在Predicate Format String Syntax中更多地解释你可以用它做什么。
不是
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
上Sequence
这里有一个示例代码来说明/模仿:
class TestClass: NSObject {
@objc var title: String
init(title: String) {
self.title = title
super.init()
}
override var description: String {
"TestClass - title: \(title)"
}
}
let objects: [TestClass] = [TestClass(title: "Title1"), TestClass(title: "Title2")]
// In a "Swifty way
let searchedText = "Title1"
let filtered1 = objects.filter {
$0.title == searchedText
}
print("filtered1: \(filtered1)")
// With a NSPredicate, which is more Objective-C (filtering on NSArray for instance)
// But also there is a translation with Core-Data, and then fetching optimization
let filtered2 = objects.filter {
NSPredicate(format: "title == 'Title1'").evaluate(with: $0)
}
print("filtered2: \(filtered2)")
// Same, but with avoiding hard coding strings
let filtered3 = objects.filter {
NSPredicate(format: "%K == %@", #keyPath(TestClass.title), searchedText).evaluate(with: $0)
}
print("filtered3: \(filtered3)")
extension Sequence {
func filter(_ predicateFormat: String, _ args: Any...) -> [Element] {
let predicate = NSPredicate(format: predicateFormat, argumentArray: args)
return self.filter({ predicate.evaluate(with: $0) })
}
}
// With an extension similar to what does Realm
let filtered4 = objects.filter("title == 'Title1'")
print("filtered4: \(filtered4)")
// With an extension similar to what does Realm, and less hard coded string (cf filtered3 construction)
let filtered5 = objects.filter("%K == %@", #keyPath(TestClass.title), searchedText)
print("filtered5: \(filtered5)")
带输出:
$>filtered1: [TestClass - title: Title1]
$>filtered2: [TestClass - title: Title1]
$>filtered3: [TestClass - title: Title1]
$>filtered4: [TestClass - title: Title1]
$>filtered5: [TestClass - title: Title1]