Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.

In our ongoing quest to build better apps, it's important for us to keep up as new techniques and best practices emerge. One such technique that's recently been growing in popularity is the use of View Models. Today we'll look at how they fit into an app, and why we'd use them.

Traditionally, we'd use the Model View Controller technique to build our apps. Sounds great, but on iOS it usually ends up looking something like this:

This approach can often lead to gigantic UIViewController subclasses, with long lists of responsibilities: networking/data loading code, table/collection view delegate methods, UI interaction, UI layout, and so on.

That's where the Model View View Model approach comes in. Don't be fooled by the name, we still need view controllers. When applied on iOS, MVVM ends up looking something like this:

We'll add a new view model type in between our model and view controller. Our view model will take over loading data, as well transforming/processing that data. Then it will expose that transformed data as read-only properties.

struct SpaceshipViewModel {
  private var ship: Spaceship

  let displayName: String { "\(ship.squadron): \(ship.name)" }
  func loadShips(start: Int = 0) { ... }

With our new View Model, we now have a clear place to put things like networking, data persistence, and all our business logic. Our view controllers can now relax a bit and handle things like user input and size class changes. Next time, we'll look at how we can make our view controller automatically react to changes in the view model.

Author's Note: Interested in learning more about this? This introduction from Bob Spryn is fantastic. It covers everything from start to finish and does a great job explaining both the "why" and "how" along the way. Highly recommended reading.