Why SwiftUI @State property can be initialized inside `init` this OTHER way:

I believe it's because StateObject applies private(set) modifer to its wrapped value. The code demonstrates the same behavior.

@propertyWrapper
struct DummyWrapper<T> {
    private(set) var wrappedValue: T

    public init(wrappedValue: T) {
        self.wrappedValue = wrappedValue
    }
}

struct Test {
    @DummyWrapper var x: Int

    init(x: Int) {
        // This works
        // _x = DummyWrapper(wrappedValue: x)

        // Error: cannot assign to property: 'x' is a get-only property
        self.x = x
    }
}

So I think the statement in SE-0528 @ole quoted above is true, as long as the wrapped property is settable in init(). That said, I also only use the underscore syntax because it's explicit and always works.


Note: as pointed by others above, just because PW initialization code compiles doesn't necessarily means it does what the user intends to do. But that's PW specific behavior.

1 Like