#propertyName in property wrappers

Inspired by the Name of a variable passed as a parameter or a generic type.

Knowing a property name in the property wrapper actually seems to be a pretty common need.

What if we introduce #propertyName similar to #function and #file. But it is accessible only in two places - as a default value of the parameter of the property wrapper's initializer or static subscript.

struct Wrapper<Value> {
  init(wrappedValue: Value, key: String = #propertyName) {

  static subscript<EnclosingSelf>(
      _enclosingInstance observed: EnclosingSelf,
      wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
      storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>,
      key: String = #propertyName
    ) -> Value {

I think this is an important problem to solve, though I'm not sure of the best way to solve it. Just to clarify, would the default argument be unavailable if you were to use the property wrapper directly? For instance, Wrapper(wrappedValue: 3) won't compile.

Yes, correct.

Terms of Service

Privacy Policy

Cookie Policy