Designing a ViewModel
Build an @Observable view model for a screen.
A ViewModel Is Just a Class
A ViewModel is usually a class that holds the state and logic for one screen. Using a class lets several views share the same live instance.
class ProfileViewModel {
var name: String = ""
}Make It Observable
Add the @Observable macro so SwiftUI tracks property changes and re-renders the view automatically when state updates.
@Observable
class ProfileViewModel {
var name = ""
}All lessons in this course
- Why MVVM Fits SwiftUI
- Designing a ViewModel
- Binding Views to ViewModels
- Dependency Injection for ViewModels