MVVM in SwiftUI - Part 1 | Understanding Pattern

MVVM in SwiftUI - Part 1 | Understanding Pattern
Photo by Tommy / Unsplash

MVVM stands for Model, View, View Model. It’s an architectural pattern that was made to separate UI Logic from the Business Logic. MVVM was first introduced to the public by Microsoft's John Gossman blog post about Avalon (the code name for Windows Presentation Foundation, or WPF).

Responsibilities of each component in MVVM

View - The View is responsible for rendering the user interface (UI) and capturing user input. It's implemented as a SwiftUI struct that defines the layout, appearance, and behaviour of the UI. It's not aware of the business logic and the data model.

Model - The Model is responsible for representing the data of the app. It typically consists of classes or structs that encapsulate the data and provide methods for manipulating and accessing it.

ViewModel - The ViewModel acts as a middleman between the Model and the View, transforming the data from the Model into a form that can be displayed by the View. It typically consists of a class that encapsulates the business logic and data processing logic of the app.

Benefits of using MVVM

Separation of concerns: MVVM separates the concerns of the app into distinct components, making it easier to maintain and test the app.

Improved testability: Because the business logic is separated from the UI, it's easier to write unit tests for the ViewModel without having to interact with the UI.

Improved maintainability: Separating the concerns of the app makes it easier to make changes to the codebase without affecting other parts of the app. This makes it easier to add new features or refactor the codebase as needed.

Data flow between components

  • The View sends user input to the ViewModel via a method call or a property binding.
  • The ViewModel processes the input and interacts with the Model to retrieve or update data as needed.
  • The ViewModel transforms the data into a format that can be easily displayed by the View. This may involve formatting the data, filtering it, or combining it with other data.
  • The transformed data is sent back to the View via a @Published property, which triggers an update to the UI.
  • The View renders the updated data to the user.
MVVM data flow