Member-only story

MVVM: A Tutorial and Practical Example in Swift

MVVM rather than MVC? What are the differences, and why should we care? Here is an explanation, with a few diagrams (and an example) to help!

5 min readOct 14, 2019

--

A representation of the MVVM model

MVVM was proposed by John Gossman in 2005. Interestingly the view should consist only of visual elements — and not make network calls or similar.

All architectures have advantages and disadvantages, but MVVM has become increasingly popular in implementations.

Some want a video, and here is one (it covers a slightly different example than the one in this article so they go well together!).

Prerequisites:

  • Some understanding of OO terminology and practices
  • Swift’s Result type is used later in the post

Terminology

Binding: The mapping of one thing to another.

View Controller: Sits between the view and the model, tying them together (usually using the delegate pattern). The controller is not tightly bound to a concrete view, and communicates via a protocol to an abstraction. An example of this is the way that a UITableView communicates with its data source through the UITableViewDataSource protocol. Think of it as the how of the App. The primary job of the controller is to format the data from the model for the view to display.

Model: Where data, and logic that manipulates the data is stored. Perhaps model objects, or networking code is stored here.Think of this as the what of the App.

View: Present information to the user. Views are, well, UIViews and their subclasses. Think of it as the UI components that have to be controlled by the controller.

ViewModel: Contains fields that are to be displayed in the view.

Discussion

MVC is often called Massive View Controller. Surely there is a better way?

--

--

Responses (1)