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?
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
mainbranch of the Swift toolchain behind the experimental feature flagInitAccessors, so if you want to play around with it, you can by switching to themainbranch 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.