20

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?

Chris Prince
  • 7,288
  • 2
  • 48
  • 66
  • I'm almost certain there's no API for doing that. – Alexander Oct 26 '19 at 23:29
  • Could this be an xy question? What’s the real goal? – matt Oct 27 '19 at 00:02
  • 3
    `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. – Chris Prince Oct 27 '19 at 02:14
  • I'm in a similar situation. Did you ever find an answer? – Dustin Pfannenstiel Nov 13 '19 at 17:23
  • Unfortunately, no. Need something like `#var`, analogous to `#function` (see https://stackoverflow.com/questions/24402533/is-there-a-swift-alternative-for-nslogs-pretty-function). I need to put this on the Swift dev forum. – Chris Prince Nov 14 '19 at 19:31
  • Some ideas here https://stackoverflow.com/questions/35114064/swift-reflection-capabilities-how-to-get-an-instance-variable-name but haven't tried this. – Chris Prince Nov 14 '19 at 19:34
  • Interested in this and hoping there can be an answer! – Patrick Mar 13 '20 at 01:24

1 Answers1

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 ) )

YodagamaHeshan
  • 4,996
  • 2
  • 26
  • 36
  • 1
    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. – Chris Prince Feb 02 '20 at 18:02
  • @ChrisPrince yeah i agree – YodagamaHeshan Feb 03 '20 at 05:49