SwiftUI Opinion: ViewModel doesn’t belong in Previews

Dave Poirier
Swift2Go
Published in
2 min readMay 22, 2022

--

SwiftUI Previews are key to making SwiftUI development fast and easy. However, if your views require a ViewModel, you are impeding your own development speed and re-usability of the view.

Photo by Łukasz Rawa on Unsplash

Let’s imagine that you create a view and it’s view model. Everything works, the project is released and everyone is happy. A couple months after, a new feature is added and you need another view that looks 100% like the one you implemented, except the logic in how the view is used is entirely different.

You find yourself having to either duplicate the SwiftUI view, or refactor the one you had created so it’s no longer tightly coupled, jeopardizing the stability of the already developed feature.

If your view requires interaction with a view model, you should extract all the visible parts of the view into its own SwiftUI view, keeping it agnostic of the view model. You end up with two SwiftUI views, one with knowledge of the view model that doesn’t have any design whatsoever in it, and another with all the design and no reference to the view model.

Example of what NOT to do:

Example of reusable design:

In a MVVM architecture, the logic is moved into a view model to allow testing the logic separately from the user interface.

Isolating a designed view from the view model improves re-usability of the view.

As a side effect, creating your Previews will be easier. You no longer have to find a way to bring the view model into the expected state, or have to create mock view models.

--

--

Dave Poirier
Swift2Go

Senior iOS Developer | Mobile Security And Reliability Specialist