Binding View Models to Views
Connect view models with SwiftUI and Combine.
Connecting ViewModel to View
A ViewModel is only useful when the View reacts to its changes. In SwiftUI this reactivity is powered by the Combine-based property wrappers @Published, @StateObject, and @ObservedObject.
Together they form an automatic binding: when the ViewModel changes, the View re-renders.
ObservableObject
To be observed by SwiftUI, a ViewModel must conform to ObservableObject. This protocol gives it an objectWillChange publisher that fires before any change.
final class CounterViewModel: ObservableObject {
@Published var count: Int = 0
func increment() {
count += 1
}
}All lessons in this course
- The MVVM Pattern
- Binding View Models to Views
- The Coordinator Pattern
- Testing View Models