[swift-evolution] Smart KeyPaths

Martijn Walraven martijn at martijnwalraven.com
Sat Mar 18 07:47:29 CDT 2017

> Smart KeyPaths: Better Key-Value Coding for Swift
> Proposal: SE-NNNN
> Authors: David Smith <https://github.com/Catfish-Man>, Michael LeHew <https://github.com/mlehew>, Joe Groff <https://github.com/jckarter>
> Review Manager: TBD
> Status: Awaiting Review
> Associated PRs:
> #644 <https://github.com/apple/swift-evolution/pull/644>
> Introduction
> We propose a family of concrete Key Path types that represent uninvoked references to properties that can be composed to form paths through many values and directly get/set their underlying values

Really happy to see this proposal! What isn’t clear to me is if/how this design could also be used for dynamic paths through collections. A concrete use case of this would be getting/setting values in a JSON response consisting of nested dictionaries and arrays.

I’ve recently started using a design similar to that described by Ole Begemann in this blog post: https://oleb.net/blog/2017/01/dictionary-key-paths/ <https://oleb.net/blog/2017/01/dictionary-key-paths/>

That allows me to use strings as key paths to navigate a nested structure:
data[keyPath: “person.bestFriend.name"] = “Han Solo”

It uses labeled subscripts to get back values of a known type, which is useful if you want to modify an array for example:
data[arrayAt: “person.friends"]?.append(["name": “Luke Skywalker”])

Generic subscripts might make this more elegant, although it seems you’d still need a way to provide enough context to let the type be inferred, and I’m not sure where that information would come from with these dynamic structures.

Curious to hear if this proposal would help with use cases like this!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170318/adbe5524/attachment.html>

More information about the swift-evolution mailing list