为具有@propertyWrapper 成员的结构合成初始化

Synthesised init for a struct with @propertyWrapper members

SwiftUI 的 @State 属性 包装器有什么魔力,这意味着我可以这样做吗?:

struct A {    
    @State var s: String
}

let a = A(s: "string") //uses a synthesised init for `A` which allows me to init A with the underlying type of `A.s` - a `string`

而如果我自己滚动 @propertyWrapper,我不能吗?

@propertyWrapper
struct Prop<Value> {
    var value: Value
    var wrappedValue: Value {
        get { value }
        set { value = newValue }
    }
}

struct B {
    @Prop var s: String
}

let b = B(s: "string") // Compiler error: `Cannot convert value of type 'String' to expected argument type 'Prop<String>'`
let b = B(s: Prop(value: "string")) // Works, but is ugly

记录在:

...你 可以 让编译器为你做这件事,就像 @State 一样 - 只需添加一个特定的魔法 init(wrappedValue:)您的 属性 包装器定义:

@propertyWrapper
struct Prop<Value> {
    var value: Value
    var wrappedValue: Value {
        get { value }
        set { value = newValue }
    }

    // magic sauce
    init(wrappedValue: Value) {
        self.value = wrappedValue
    }
}

struct B {
    @Prop var s: String
}

let b = B(s: "string") // Now works

顺便说一句,这还允许您在结构定义中为包装的属性分配默认值:

struct B {
    @Prop var s: String = "default value" // Works now; would have thrown a compiler error before
}