UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

What is MVVM?

Swift version: 5.6

Paul Hudson    @twostraws   

MVVM stands for “Model View ViewModel”, and it’s a software architecture often used by Apple developers to replace MVC.

In MVC the way most Apple developers practice it, the view controller forms part of the Controller layer (the C in MVC), which means it’s responsible for doing lots of layout as well as being a general dumping ground for functionality.

In MVVM view controllers are considered part of the V layer, which means their job is to focus specifically on layout and the view lifecycle – viewDidLoad() and so on. In its place a new object is created called the view model, which is effectively most of the code you had in your view controller before except without UIKit attached. That is, it should be capable of responding to requests for data, and so on, except it shouldn’t reference any user interface controls.

This might seem like you’re just pointlessly moving code around, but the difference is important: because your view model is more like a model than like a view you can write tests for it more easily. Rather than having to mock up a UITextField to insert some data, you should be able to call a method that accepts a string because your view model shouldn’t rely on any user interface components.

While all this sounds positive, MVVM does have a big drawback on iOS: it relies on a system of two-way bindings that can communicate view data to your view model, otherwise you need to do a lot of work shuttling data around yourself.

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS – learn more in my book Swift Design Patterns

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.