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

Michael J LeHew Jr lehewjr at apple.com
Wed Apr 5 12:23:04 CDT 2017


> On Apr 3, 2017, at 1:47 PM, Joshua Alvarado via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Example:
> struct Foo {
>     var firstName: String
>     var lastName: String
> }
> 

You would need to spell out #keyPath(Foo, .firstName) here, or decorate the type on keyPaths like so:

let keyPaths : [KeyPath<Foo, String>]  = ... or let keyPaths : [PartialKeyPath<Foo>] = ...  to use the short hand in your value declaration.  The difference between the two is that the PartialKeyPath lets you refer to non-string properties, whereas the other is more strongly typed. 

> let keyPaths = [#keyPath(.firstName), #keyPath(.lastName)]

The same would be true on the inference:

> let keyPaths = [#keyPath(Foo, .firstName), #keyPath(Foo, .lastName)]

Infers that keyPaths is a [KeyPath<Foo, String>] since everything agrees;

let keyPaths = [#keyPath(Foo, .firstName), #keyPath(Foo, .age)] // suppose it returns Int

Would only be able to infer up to PartialKeyPath<Foo>.

> for key in keyPaths {
>     foo[keyPath: key] = "bar"
> }
> 
> print(foo) // firstName = bar, lastName = bar

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


More information about the swift-evolution mailing list