[swift-evolution] SE-0062 Referencing Objective-C key-paths

Brent Royal-Gordon brent at architechies.com
Tue Apr 12 04:14:02 CDT 2016


> 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
> 
> chris
> .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”]
> or maybe
> chris.valueOf(#keyPath(Person.friends.firstName)) // => ["Joe", "Douglas”]

Interesting.

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!

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list