Chr*_*nce 13 swift property-wrapper
I'm using Swift property wrappers to define something like:
@MyWrapper var foo: Int
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Suggestions?
将变量名称传递给包装器;你可以使用这种替代方式。
@propertyWrapper
public struct MyWrapper<Type> {
var wrappedValue: ... {
set{.....}
get{.....}
}
init(wrappedValue initialValue: Double, _ nameOfTheVariable: String ) {
precondition(!nameOfTheVariable.isEmpty)
//you can access nameOfTheVariable here
}
}
Run Code Online (Sandbox Code Playgroud)
然后像下面一样使用它,
@MyWrapper("foo") var foo: Int
Run Code Online (Sandbox Code Playgroud)
注意:在 init 方法中必须提到wrappedValue。除非,它对我不起作用。
( init( wrappedValue初始值: Double, _ nameOfTheVariable: String ) )
| 归档时间: |
|
| 查看次数: |
880 次 |
| 最近记录: |