swiftswiftuiobservableswift-macro

@Observable initial value with classes


Converting from ObservableObject to @Observable macro, an initial value is required but initializing from init fails:

@Observable final class ViewModel {
    var foo: Foo // ❌ @Observable requires property 'foo' to have an initial value (from macro 'Observable')

    init(foo: Foo) {
        self.foo = foo
    }
}

The macro seemingly requires initialization twice (with an initial value that will be immediately discarded). Is there a reasonable solution to this using classes for view models?


Solution

  • This actually seems like a limitation of the language itself. The SE-0400 evolution proposal aims to tackle this exact problem.

    The proposed solution is already implemented on the main branch of the Swift toolchain behind the experimental feature flag InitAccessors, so if you want to play around with it, you can by switching to the main branch version of the toolchain and enabling this feature flag.

    Unfortunately there doesn't seem to be a workaround for this problem without the proposed compiler changes being accepted and released.