Instruction
MVVM is a Clean Architecture. Its three layers have separate responsibilities:
- The Model Layer contains data access objects and validation logic. It knows how to read and write data, and it notifies the view model when data changes.
- The View Layer styles and displays on-screen elements. It doesn’t contain business or validation logic. Instead, it binds its visual elements to properties on the view model. It also receives user inputs and interaction, and it calls methods on the view model in response.
- The View Model Layer contains the state of the view and has methods to handle user interaction. It calls methods on the model layer to read and write data, and it notifies the view when the model’s data changes.
As a result, the view layer and model layer are completely decoupled. The view layer and model layer only communicate with the view model layer. In “traditional” MVVM, each view has its own view model, but in SwiftUI, which encourages you to extract subviews, a view model for each view isn’t practical. It’s more useful to have a view model for each data model entity or for tasks like animation or form validation. For example, this app has a view model for Movies and another for Users.
When a SwiftUI view model manages CRUD (Create Read Update Delete) operations for a data model entity, it’s often called a “store”: MovieStore
and UserStore
.
Next up is a demo to see how this works in a SwiftUI app.