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?
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to