Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 368
Chris Prince Avatar asked Oct 26 '19 22:10

Chris Prince


People also ask

How do you use property wrapper in Swift?

This property can have any type you want. To access this property, you need to add a $ prefix to the property name. To explain how it works, we use an example from the Combine framework. The @Published property wrapper creates a publisher for the property and returns it as a projected value.

What is wrappedValue in Swift?

A projection of the binding value that returns a binding. Returns a binding to the resulting value of a given key path.

How do I make a property wrapper?

You can create a Property Wrapper by defining a struct and marking it with the @propertyWrapper attribute. The attribute will require you to add a wrappedValue property to provide a return value on the implementation level.

What are property observers in Swift?

Property Observers. Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.


1 Answers

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

like image 195
Yodagama Avatar answered Sep 18 '22 13:09

Yodagama