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

Andrey Volodin siddok at gmail.com
Wed Apr 12 09:48:20 CDT 2017


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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170412/a0880714/attachment.html>


More information about the swift-evolution mailing list