Initialise Property Wrapper in the init

19 Views Asked by At

I have the following simple property wrapper

@propertyWrapper
struct TestWrapper<Value> {
    private var value: Value
    
    init(wrappedValue: @autoclosure @escaping () -> Value) {
        self.value = wrappedValue()
    }

    var wrappedValue: Value {
        mutating get {
            return value
        }
        set {
            value = newValue
        }
    }
}

What I want to do is to define a property with it in a custom type and initialize it in the init and not in the declaration, like the following:

struct TestValueContainer {
    @TestWrapper var testValue: String
    
    init() {
        testValue = "Initial Value"
    }
}

This does not work and I'm getting a compile time error like

'self' used before all stored properties are initialized

How can I make this work?

0

There are 0 best solutions below