0Pricing
Swift Academy · Lesson

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

  1. The MVVM Pattern
  2. Binding View Models to Views
  3. The Coordinator Pattern
  4. Testing View Models
← Back to Swift Academy