When I saw @Observable
in the Platforms State of the Union on day 1 of WWDC, I rushed to make a tutorial that would make use of it. Instead of a model class inheriting from ObservableObject
and marking its properties as @Published
, we can now simply mark the model class as @Observable
.
It was necessary to import SwiftData
, which is a new framework that makes it easier to save data persistently. I won’t be doing that, but it isn’t possible to use @Observable
if I don’t import it. I also have to import
Foundation
in order to access Double, which I’m using to store the width of a Rectangle
in my view.
I couldn’t figure this tutorial out a week ago because @Observable
isn’t compatible with @ObservedObject
. This is what was previously used to access a model class that inherits from ObservableObject
, and code such as $model.width
can be used to access the @Published
properties within that class.
Doing that now will cause an error.
Now we can actually use @State
for the model, which was previously only used for local properties inside the ContentView
.
This is also the first time I’ve used #Preview
, which is a far easier way to show what you want in the SwiftUI Preview Canvas.