class Human { var firstName: String var lastName: String var birthdate: String } // Converts Human object into formatted View Model class HumanViewModel { // Some call it ViewData var fullName: String var ageInDays: Int var birthdateDayMonth: String } // UIKit reusable View class HumanListViewController { … } // UI-independent data layer class HumanListViewModel { var people = [HumanViewModel]() func fetchPeople() {} } Any view can use Model to show data. Usually model is a bunch of strings+numbers+booleans. ViewModel is formatted model, ready to appear in View. Any ViewController can have a ViewModel to move all data logic into ViewModel. Any View can use a ViewModel to show formatted data in cells. All formatting should go into ViewModel.
/ Coordinator linked with MVVM/MVC can) 2. Doesn't handle API (Moya could help us here) 3. Many responsibilities (Network, Data logic, Presentataion logic) 1. Maintainable (Separates UI and data handling) 2. Testable (We can test data formatting/mapping without affecting UI components) 3. Reusable (We can use one VC / VM for different screens) 4. Easily convertible from MVC (Can be used as starting point to better architecture) Con’s Pro’s 2. Why we should use MVVM
var submitButton: UIButton @IBAction tapSubmit() { viewModel.fetchPeople() } } // UI-independent data layer class HumanListViewModel { var people = [HumanViewModel]() func fetchPeople() {} } MVVM: • Never reference the view controller • Do not import UIKit. Make it a different file • Do not reference anything from UIKit. Even buttons. • It should only be data, i.e., strings, structs, JSON