Why does @Observable need an initial value?

Why would it not allow to set the value in the init statement. The @Model allows this and as I understand it also acts as an @Observable.

Replies

For… well… reasons (-:

One of the nice things about Swift is that it’s all developed in the open, so you can answer Why? questions. In this case, this limitation is specifically called out in the Future Directions section of the Swift Evolution proposal, SE-0395 Observation. If I understand things correctly, there’s an in-flight pitch that would help with this. See this comment by Philippe, the same Philippe who presented this session. However, I only lurk on Swift Evolution, so I’m not really up-to-speed on all the details.

Regardless, if you want to get involved in how this pans out, pop on over to Swift Evolution and wade in (-:

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

We need something, especially since the new @Observable macro throws these non-initialized errors and breaks quite a few property wrappers in the process, including the @Injected property wrapper types used in Factory and other dependency injection systems.

@Observable
class SplashScreenViewModel {
    @Injected(\.loginService) private var loginService: LoginServices
    ...
}

In Factory, the keypath initializer points to a DI container/factory that will provide the requested service. An initialized variable isn't needed (or even possible).

The @Observable macro basically breaks any property wrapper like this one whose job it is to pull a keyed value from a container, database, or other backing store.

You can "fix" the problem with @ObservationIgnored, but that needs to be done every single time a property wrapper is used, which in turn greatly discourages their use.

@Observable
class SplashScreenViewModel {
    @ObservationIgnored @Injected(\.loginService) private var loginService: LoginServices
    ...
}

It would be better if, as mentioned in this proposal, there was a away to mark the property wrapper itself as fulfilling any needed requirements.