MVVM with SwiftUI and Combine

Karthik
2 min readNov 7, 2021

--

With SwiftUI, you’re already 90% towards working with MVVM

Let’s get started

In this article, we gonna migrate the UIKit implementation (#1) to turn the MyPortfolio app into SwiftUI.

Model

We’re going to keep the same model as the UIKit implementation. Additionally, we are going to implement the Codable & Identifiable protocol on the model for effective handling.

Sample model with Codable & Identifiable

View

Instead of using traditional UIKit’s UITableViewCell for constructing cells, we are going to use the SwiftUI approach of creating rows. With the help of SwiftUI’s View protocol, the view is constructed to represent each row. Hence the row implementation looks like the following sample.

Sample row with SwiftUI

ViewModel

The ViewModel provides a set of properties that represents each UI component available in the View. ViewModel and UI Controls are connected with the combined framework techniques ObservableObject & Published.

When you adopt ObservableObject protocol in your class (ViewModel), you’re essentially turning the class instances into publishers that can emit values to anyone who subscribes to them. This is a core principle of the Combine framework

The @Published property wrapper essentially turns the property (instruments) into a publisher. That means you can subscribe to the property and respond to changes the publisher emits

Sample Observable ViewModel

Screen

InstrumentsViewController is replaced by InstrumentsScreen, for the naming convention, we are going to keep the screen prefix for all of our SwiftUI Screens that replace view controllers.

Once the screen is constructed, a ViewModel which is of type ObservableObject instance is added under the screen for observing list changes.

Sample instrumentsScreen

Final App

After doing all the migration from the native UIKit to SwiftUI, the final result looks like this. InstrumentsScreen is just wrapped under the Navigation stack for route handling.

Wrapping Up

We have done the migration of “MyPortfolio” using MVVM + Combine + SwiftUI. In, upcoming weeks we can derive a new combination with the following MVVM patterns :

I hope you enjoyed this article 😀. Please feel free to share, comment, and give some claps 👏👏. Stay tuned at this pace for more updates. Thanks for reading this.

--

--