What is MVVM and how the hell does it work?
--
As soon as I started learning SwiftUI, I just focused on how to build nice views and all of the stuff that brings all the newbies and us, ruined by life-constraints-UIKit developers to SwiftUI. First impression? Nice! But how do I deal with real world problems now?
It popped to my head that I knew pretty much nothing about MVVM → impossible to create real apps. But now I kind of do. I’m not an expert (yet) but I make it all work smoothly so hopefully you will too after today.
MVVM
MVVM stands for Model View View-Model.
The way I see it, the main focus of this pattern is the View-Model, as we should already be familiar with the model and the view. Anyway for those of you who aren’t, don’t worry: I explained below what they are and you’ll agree with me they’re not a big deal after all.
Model:
The model contains the data and the logic of the app, describing how it will behave. It’s the skeleton, it doesn’t have to know about the view. Therefore, we won’t import SwiftUI in the model files.
Example:
Imagine we have a random game where we need to define a player. The model of the app would have a Player struct containing the player data (name, points, level, exp) and some functions we can use on that player (levelUp(), addPoint(), ecc.).
The model can also be a database but I won’t cover how to implement it in this article sadly.
View:
The view is what the user sees and it is a reflection of the model. This means the view will display data retrieved from the model. To retrieve model data, the view has to interrogate the View-Model.
Gets data from model by asking it to the viewmodel
ViewModel:
The View-Model is a class containing the state of the associated views and some operations on the data. It basically connects the view and the model.
A few important theoretical notes about the View-Model:
- It never saves data from the model, it just helps manipulating it with some operations that we can call from the model;
- It is ALWAYS a…