I very much like this proposal but what bothers me is this doubling of valueForKeyPath(#keyPath(xxx) in the signature of the function.
chris.valueForKeyPath(#keyPath(Person.bestFriend.lastName)) // => Groff
.valueForKeyPath(#keyPath(Person.friends.firstName)) // => ["Joe", "Douglas"]
I’m not sure whether the form below is actually possible. For me it reads more naturally and is more consistent with “Modern Swift” as far as I know.
chris.valueFor(#keyPath(Person.friends.firstName)) // => ["Joe", "Douglas”]
chris.valueOf(#keyPath(Person.friends.firstName)) // => ["Joe", "Douglas”]
If Foundation, Core Data, AppKit, and other frameworks properly annotated their APIs, I think we could actually get this from the already accepted SE-0033 "Import Objective-C Constants as Swift Types" <https://github.com/apple/swift-evolution/blob/master/proposals/0033-import-objc-constants.md>. Specifically, Foundation would have to include this typedef:
typedef NSString * NSKeyPath __attribute__((swift_wrapper(struct)));
And all APIs with string types which were actually key paths would have to be modified to use it. Then `-(nullable id)valueForKeyPath:(NSKeyPath)keyPath` would import as `func value(for: NSKeyPath) -> AnyObject?`. This proposal's `#keyPath` construct would have to then construct an `NSKeyPath` instead of a `String`.
(To make this all work, it might make sense to add a KeyPathLiteralConvertible protocol to the standard library. As a bonus, if this protocol's initializer received enough metadata, it might be able to construct alternate forms of key paths, such as the Rails-style ones which handle arrays somewhat differently from Foundation's.)
This is more work, but it's also more general, which is a pretty cool prospect!