> I wish CoreData (or similar object-to-relational-mapping module) in Swift
> eventually leverage smart keys and key paths to make our code beautiful when
> building sort orderings, qualifiers (predicates or whatever they are called
> in CoreData) to build queries or apply them in-memory to arrays. This is
> what I do every day.
>
> For example, wouldn't it look much nicer if some day you could express the
> above like this in Swift:
>
> let isPuppyQualifier = Pet.type.equals(.dog).and(Pet.age.lessThan(12))
> let familyQualifier = Family.pets.hasAtLeastOne(satisfying: isPuppyQualifier)
> let familiesWithPuppies = Family.fetch(editingContext, familyQualifier)
>
> For those unfamiliar with EOF, the editingContext in the code above is an
> EOEditingContext which is analogous to NSManagedObjectContext.
Theoretically, you could do something like that with this proposal...
struct UnaryPredicate<Parameter, Result> {
let evaluate: (Parameter) -> Result
}
struct BinaryPredicate<Left, Right, Result> {
let evaluate: (Left, Right) -> Result
}
extension KeyPath where Value: Equatable {
func equals(_ value: Value) -> UnaryPredicate<Root, Bool> {
return UnaryPredicate { $0[keyPath: self] == value }
}
func equals<KP: KeyPath>(_ other: KP) -> BinaryPredicate<Root, KP.Root,
Bool> where KP.Value == Value {
return BinaryPredicate { $0[keyPath: self] == $1[keyPath: other] }
}
}
let isDog = #keypath(Pet, .type).equals(.dog) // UnaryPredicate<Pet, Bool>
if isDog.evaluate(somePet) {
print(“It’s a dog”)
}
let areSameLength = #keypath(Array<Int>, .count).equals(#keypath(Array<String>,
.count))
// BinaryPredicate<Array<Int>, Array<String>, Bool>
if areSameLength.evaluate([1,2,3], [“a”, “b”, “c”]) {
print(“same lengths”)
}
but the syntax isn’t as nice when you start chaining key paths together because
#keypath() is a little loud. No doubt there will be plenty of libraries for
this sort of thing, though.
- Karl_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution