Skip to content

Out-of-line-initialized property wrapper incorrectly diagnosed as error if wrappedValue is read-only #63261

Open
@ole

Description

@ole

Description

Swift 5.7.2 incorrectly refuses to compile out-of-line initialization of a property wrapper via the wrapped property if the property wrapper's wrappedValue is read-only or inaccessible.

Example (thanks to Huan Xiong) (note the error in the self.x = x line):

@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) {
        // Error: cannot assign to property: 'x' is a get-only property
        self.x = x

        // This works:
        // self._x = DummyWrapper(wrappedValue: x)
    }
}

According to SE-0258: Property wrappers > Out-of-line initialization of properties with wrappers, this should be legal:

A property that has a wrapper can be initialized after it is defined, either via the property itself (if the wrapper type has an init(wrappedValue:)) or via the synthesized storage property

The code compiles fine if you remove the private(set) from the wrappedValue declaration. The diagnostic "cannot assign to property: 'x' is a get-only property" suggests that the compiler wants to access the property wrapper's wrappedValue setter here, even though we're dealing with initialization.

Initially discussed in this thread: https://forums.swift.org/t/why-swiftui-state-property-can-be-initialized-inside-init-this-other-way/62772/26

Environment

$ swiftc -version
swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
Target: arm64-apple-macosx13.0

$ xcodebuild -version
Xcode 14.2
Build version 14C18

Metadata

Metadata

Assignees

No one assigned

    Labels

    accessorsFeature → declarations: Variable (property) accessorsbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfproperty wrappersFeature: property wrapperstype checkerArea → compiler: Semantic analysis

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions