[swift-evolution] [Review] SE-0161: Smart KeyPaths: Better Key-Value Coding for Swift

Karl Wagner razielim at gmail.com
Sat Apr 1 19:56:24 CDT 2017


> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170402/0bc56ee2/attachment.html>


More information about the swift-evolution mailing list