[swift-evolution] Unify the way properties and methods work to make key-value coding more natural

Joe Groff jgroff at apple.com
Wed Apr 12 15:13:55 CDT 2017


> On Apr 12, 2017, at 7:48 AM, Andrey Volodin via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Recently I’ve seen some upcoming changes for #keyPath, but the whole things look a bit messy to me. Today I came up with a simple idea of code generation, but I thought maybe it would be nice to make this a part of the language?
> 
> Look at this code:
> 
> public class Foo {
>     public var a: Int = 0
> }
> 
> public final class Property<U, V> {
>     public var `get`: (U) -> () -> V
>     public var `set`: (U) -> (V) -> Void
>     
>     public init(getter: @escaping (U) -> () -> V, setter: @escaping (U) -> (V) -> Void) {
>         self.get = getter
>         self.set = setter
>     }
> }
> 
> // Generated code
> public extension Foo {
>     public static let a: Property<Foo, Int> = {
>         return Property<Foo, Int>(getter: { instance -> (Void) -> Int in
>                                             return { return instance.a} },
>                                   setter: { instance -> (Int) -> Void in
>                                             return { value -> Void in instance.a = value } })
>     }()
> }
> 
> let foo = Foo()
> foo.a = 5
> 
> let _a = Foo.a.get(foo)()
> print(_a)
> 
> Foo.a.set(foo)(10)
> print(foo.a)
> 
> The idea is to make properties work the same way the methods work right now. That will allow things like tweening properties in the game engine, by simply passing the property to some sort of ActionManager.
> 
> Of course, this can be achieved by code-generator, but I bet this will be very ineffecient in terms of performance. 
> 
> The only draw back here from top of my head: It will be impossible to have instance- and static- variables with the same name. 
> 
> What do you think about this?

KeyPath<T, U> is pretty much exactly your Property<T, U>; however, keypaths are also intended to support equality as well as other reflective features down the line, so they need a bit more information under the hood than just an opaque closure. Our original proposal suggested exactly this syntax, but we rejected it because we felt like the unapplied member syntax looks too much like a concrete property/method reference, even in its existing form for methods. While the \ syntax will only apply to key paths to begin with, we want to look into unifying all unapplied member references under that syntax.

-Joe

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


More information about the swift-evolution mailing list