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?
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.
A projection of the binding value that returns a binding. Returns a binding to the resulting value of a given key path.
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.
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.
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 ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With