Properties forwarding (aliasing)

One of the future directions for Property Wrappers is " Referencing the enclosing 'self' in a wrapper type"
With that you could make a forwarding wrapper:

@propertyWrapper
public struct Forward<Value, Root> {
  private let keyPath: WritableKeyPath<Root, Value>
  
  public init(_ keyPath: WritableKeyPath<Root, Value>) {
    self.keyPath = keyPath
  }
  
  public subscript(instanceSelf: Root) -> Value {
    get { instanceSelf[keyPath: self.keyPath] }
    set { instanceSelf[keyPath: self.keyPath] = newValue }
  }
}

// used like this
struct Foo {
  var someProperty: String
  @Forward(\.someProperty) var thisIsAnAlias: String
}
1 Like

:+1:
The Kotlin language already has an idiom for specifying protocol or class conformance by forwarding its interface to a property: https://kotlinlang.org/docs/reference/delegation.html

Note that this idiom encourages "composition over inheritance" and fits well with protocol-oriented programming.

1 Like

I pitched protocol-based forwarding in the early days of Swift evolution. There are some nuances around Self and associated types in Swift that I don’t believe are relevant to Kotlin. There was good discussion and I started working on a second draft of the proposal. I dropped it when it became clear it was not going to make it into Swift 3. I would like to revisit that topic someday.

3 Likes