Access name of object being wrapped, in Swift property wrapper implementation
Asked Answered
K

1

21

I'm using Swift property wrappers to define something like:

@MyWrapper var foo: Int

And in the implementation of the property wrapper, I'd like to access the name of the variable, foo, as a string. Something like this:

@propertyWrapper
public struct MyWrapper<Type> {
  init() {
    // Get access to "foo" -- name of var as String
  }
}

Suggestions?

Kentiga answered 26/10, 2019 at 22:51 Comment(8)
I'm almost certain there's no API for doing that.Poler
Could this be an xy question? What’s the real goal?Protractor
xy question? In the @propertyWrapper implementation I need a name that I use to store data in, say, user defaults-- specific to this property. I can (and am doing this now) pass the name as an init parameter. But, it seems cleaner to at least give a parameter default that's the name of the variable.Kentiga
I'm in a similar situation. Did you ever find an answer?Bodgie
Unfortunately, no. Need something like #var, analogous to #function (see #24403033). I need to put this on the Swift dev forum.Kentiga
Some ideas here #35114564 but haven't tried this.Kentiga
Interested in this and hoping there can be an answer!Ravi
This should be solvable now with Swift macros!Kentiga
Z
1

To pass variable name to the wrapper; you can use this alternative way.

@propertyWrapper
public struct MyWrapper<Type> {

  var wrappedValue: ... {
  set{.....}
  get{.....}
  }

  init(wrappedValue initialValue: Double, _ nameOfTheVariable: String ) {
      precondition(!nameOfTheVariable.isEmpty)
      //you can access nameOfTheVariable here
  }  
}

then use it like below,

   @MyWrapper("foo") var foo: Int

Note: in the init method mentioning wrappedValue is a must. Unless , It didn't work for me.

(init(wrappedValue initialValue: Double, _ nameOfTheVariable: String ) )

Zingale answered 1/2, 2020 at 10:34 Comment(2)
Thanks for the idea, @Yodagama. However, this isn't quite what I asked. This isn't the "name of the variable" exactly. It's another string passed as a parameter. It isn't quite as good notationally, and the API user of the wrapper has to know what to pass in-- the redundant name of the variable.Kentiga
@ChrisPrince yeah i agreeZingale

© 2022 - 2024 — McMap. All rights reserved.