Reputation: 7584
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?
Upvotes: 21
Views: 1991
Reputation: 6550
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 ) )
Upvotes: 1