Chapter 10: Model-View-ViewModel Pattern
大綱
When should you use it?
Model-View-ViewModel (MVVM) is a structural design pattern that separates objects into three distinct groups:
Models : hold app data. They’re usually structs or simple classes.
Views: display visual elements and controls on the screen. They’re typically subclasses of UIView.
View models: transform model information into values that can be displayed on a view. They’re usually classes, so they can be passed around as references.
view controllers: do exist in MVVM, but their role is minimized.

When should you use it?
Use this pattern when you need to transform models into another representation for a view.
MVVM is a great way to slim down massive view controllers that require several model-to-view transformations
Playground example
Model
ViewModel
View
Configure
What should you be careful about?
MVVM works well if your app requires many model-to-view transformations.
However, not every object will neatly fit into the categories of model, view or view model. Instead, you should use MVVM in combination with other design patterns.
Tutorial project
CoffeeQuest
Key points
MVVM helps slim down view controllers, making them easier to work with. Thus combatting the "Massive View Controller" problem.
View models are classes that take objects and transform them into different objects, which can be passed into the view controller and displayed on the view. They’re especially useful for converting computed properties such as Date or Decimal into a String or something else that actually can be shown in a UILabel or UIView.
If you’re only using the view model with one view, it can be good to put all the configurations into the view model. However, if you’re using more than one view, you might find that putting all the logic in the view model clutters it. Having the configure code separated into each view may be simpler.
MVC may be a better starting point if your app is small. As your app’s requirements change, you’ll likely need to choose different design patterns based on your changing requirements.
Last updated