0

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?

amq
  • 160
  • 4
  • 17
  • Best to just use the View struct for your view data as it's designed – malhal Jun 16 '23 at 15:49
  • @malhal That is neither what this question is about nor the use case provided for `@Observable` (see the talk I linked) – amq Jun 17 '23 at 10:12
  • @amg you the talk you linked is about "Simplify your SwiftUI data models with Observation." your question has code for a ViewModel which is what the View struct is for. – malhal Jun 17 '23 at 17:10

1 Answers1

2

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116