Principle is a swift library to create compile-time checked NSPredicates, NSSortDesciptions, Filters and Comparators. Principle is compatible with CoreData. What does all that mean?
The following examples show how to construct NSPredicates and NSSortDescriptors with Principle. Note that the types in these examples are constructed without using predicate format strings.
class Person : NSObject {
@objc let name: String
@objc let age: Int
}
let orderings: [NSSortDescription] = [\Person.age|asc, \Person.name|desc]
let predicate: NSPredicate = Person.age > 30 && \.name != "Jerry"The same syntax also yields function forms:
let orderings: [(Person,Person)->Bool] = [\Person.age|asc, \Person.name|desc]
let predicate: (Person)->Bool = Person.age > 30 &&& \.name != "Jerry"Type inference usually makes the explicit types unnecessary. Thus the following are natural use cases:
let people = [Person(name: "Jerry", age: 30), Person(name: "Mike", age: 25), Person(name: "Tom", age: 35)]
let sortedPeople = people.sorted(by: \.age|asc)
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Trip.entityName())
request.predicate = \Trip.destination == "Maui, Hawaii" || \.travelers > 3
request.sortDescriptors = [\Trip.startDate|desc, \Trip.endDate|asc]Principle supports arbitrary subqueries like so:
@objcMembers
class Person : NSObject {
let id: String
let name: String?
let age: Int
var pets = Set<Pet>()
init(id: String, name: String, age: Int) {
self.id = id
self.name = name
self.age = age
}
}
@objcMembers
class Pet: NSObject {
let name: String?
let legs: Int
init(name: String?, legs: Int) {
self.name = name
self.legs = legs
}
}
let jerry = Person(id: "11", name: "Jerry", age: 50)
let michael = Person(id: "12", name: "Michael", age: 40)
let bob = Person(id: "13", name: "Bob", age: 30)
jerry.pets = [Pet(name: "Spot", legs: 4), Pet(name: "Lucky", legs: 3)]
michael.pets = [Pet(name: "Clive", legs: 2), Pet(name: nil, legs: 8)]
// ok, enough setup. Now the good stuff.
let data = [jerry, michael, bob]
let filtered1 = data.filter(\.id.count > 0 && any(\.pets, match: \.legs > 4))
let filtered2 = data.filter(\.name|hasPrefix("j") || all(\.pets, match: \.legs >= 2))
let filtered3 = data.filter(no(\.pets, match: \.legs >= 2))N.B. All of the above is compatible with CoreData.
This project is still young and the documentation is sparse. If you're having any trouble with it, contact the project owner and I'll add the necessary documentation.