<aside> <img src="/icons/eject_blue.svg" alt="/icons/eject_blue.svg" width="40px" />
Removing our state from the view
</aside>
In the apps we’ve built so far this semester, all application state was managed by a bunch of individual @State properties declared directly inside of View structs. Example:
// Super simplified ContentView from L06 - Notes App
// - All application state (newNoteContents, notes) stored in ContentView
struct ContentView: View {
@State private var newNoteContents: String = ""
@State private var notes: [Note] = []
var body: some View { ... }
}
This has worked well so far – but, we’ll need a new approach when we start using MVVM to organize the code for our apps. This is because our view models will separate, bespoke class's that are responsible for managing and storing all of our application state. And, as we’ve seen it so far this semester, the @State property only works with value types.
Luckily, SwiftUI provides a really simple tool that allows us to abstract application state into a separate class – the @Observable macro. This is a awesome tool that let’s us monitor properties inside of a class and redraw the UI when any of them change.
To learn what @Observable is and how to use it, you will check out two videos/articles by the Paul Hudson. Paul provides his content in both video and article form, so pick which one works best for you. I personally prefer to watch the videos.
Before you do that, I want to note that Paul motivates @Observable as a tool to let you share state between two views rather than as a tool to implement MVVM.
This is because, at this point in his course, he hasn’t yet discussed @Binding. This won’t matter for our purposes. I just want you to gain an initial understanding of @Observable, why we need it, and how to use it.
<aside> <img src="/icons/checkmark_blue.svg" alt="/icons/checkmark_blue.svg" width="40px" />
Action Item: Watch/read Using @State with classes. (Click Here)
</aside>
<aside> <img src="/icons/checkmark_blue.svg" alt="/icons/checkmark_blue.svg" width="40px" />
Action Item: Watch/read Sharing SwiftUI state with @Observable. (Click Here)
</aside>
<aside> <img src="/icons/checkmark_blue.svg" alt="/icons/checkmark_blue.svg" width="40px" />
Don’t forget about the questions on Gradescope!
</aside>