MVVM in iOS Swift

Abhilash Mathur
Jul 9 · 5 min read
Image for post
Image for post

Whenever we start building a new application, this question always comes in our mind, which architecture pattern to choose for our new project. The most used architectural pattern in iOS is MVC. Most of the developers used the MVC pattern for their projects. Small projects work well with MVC, but when your project size starts increases, it starts making your source code messy.

I always found the architecture pattern is good to use, but we should not strictly follow an architecture pattern in our project. Not every architecture pattern is good enough to give you everything, there are cons & pros of every architecture pattern. if we have a lot of modules in our project, we can decide the architecture pattern according to the module also. Some module suits well with MVVM, but maybe your new module will not work well with MVVM, so instead use another architecture pattern like MVP, VIPER. So we should not completely rely on a single architecture pattern, instead, we can check it according to the module also.

There are lots of articles available over the internet explaining the definition and cons and pros of the MVVM pattern. So here we will more focus on the practical implementation of the pattern instead of just reading the definition.

Let’s get started

In this project, we will be building a simple application using the MVVM design pattern. In most of our application, we have a view controller (UI) which needs to fetch data from the server(API) and need to display it in the UI. We will implement the same behavior using the MVVM Pattern.

This is our expected output at the end of this article.

Image for post
Image for post

Here we will be consuming a dummy web service publicly available over the internet.

http://dummy.restapiexample.com/api/v1/employees

This web service gives us the response of a list of employee data and we will show this list in our table view.

Components Overview and their roles

  • View Controller: It only performs things related to UI — Show/get information. Part of the view layer
  • View Model: It receives information from VC, handles all this information, and sends it back to VC.
  • Model: This is only your model, nothing much here. It’s the same model as in MVC. It is used by VM and updates whenever VM sends new updates

Let’s structure our code and creates the required files in their respective groups. So we have created 3 new files one in each group (Models, ViewModels, API Service).

Image for post
Image for post

Model

The Model represents simple data. It simply holds the data and has nothing to do with any of the business logic. You can simply say it’s a plain structure of data that we are expecting from our API.

Here we can check the response for the above URL and we will create a model class for this response. You can create a model on your own or else you can use any online model generator site.

Application flow will be like this

  1. View controller will get called and the view will have a reference to the ViewModel
  2. The View will get some user action and the view will call ViewModel
  3. ViewModel will request APIService and APIService sends a response back to the ViewModel
  4. Once we receive a response, ViewModel notifies the view through binding
  5. The View will update the UI with data

So now, we will start writing our source code in sequence. First of all the View controller will get called and from the view controller, we will call our ViewModel class. We are not doing binding between the two now. We will do that later.

Image for post
Image for post
ViewController

ViewModel

ViewModel is the main component of this architecture pattern. ViewModel never knows what the view is or what the view does. This makes this architecture more testable and removes complexity from the view.

In View Model, we will call our APIService class to fetch data from the server

Image for post
Image for post

When you write this code in view model class, it will give you errors as we have not implemented API Service class. So now let’s implement API Service class.

API Service

API Service class is a simple class where we are fetching employee data using URLSession class. you can use any networking model here to fetch data from your server. From our view model class, we will call the API Service class

Once we received an API response in ViewModel class. Now it’s time to do binding between ViewController and View Model.

MVVM Bindings

MVVM binding plays a vital role in our project. How we are communicating between the view model and view controller is important. We can do the binding in many ways.

we will create a property in view model class by named “var bindEmployeeViewModelToController”

var bindEmployeeViewModelToController : (() -> ()) = { }

This property needs to be called from the View Controller class

We will create another property in view model class by name “empData” of type Employees (Model) that retrieves those results from APIService and notify the view that there have been changes.

private(set) var empData : Employees! {

didSet {

self.bindEmployeeViewModelToController()

}

}

empData is set to the response received from API Service. By using property observer, as soon as we get value in empData as a response of API, didSet of empData is called and we have called bindEmployeeViewModelToController() inside didSet of empData

Once we received the data from the view model to view, now its time to update our UI.

View

To receive data from ViewModel class we have link our ViewModel property inside the view controller class

self.employeeViewModel.bindEmployeeViewModelToController = {

self.updateDataSource()

}

To update your UI you can write table view code on view Controller also, but to make view controller less messy or modular, Here I will create separate class EmployeeTableViewDataSource extending from UITableViewDataSource.

As I already said every architecture pattern has its cons and pros, if we have a lot of advantages of using the MVVM pattern, there are some disadvantages also.

Disadvantages of MVVM

  • For Beginners, MVVM will be hard to implement.
  • Apps with simple UI, MVVM can be overkill.
  • For larger apps, data binding will complex, So debugging will be hard

Conclusion

Here, we are done with building a sample application of MVVM architecture and its usage. Hope this is helpful. Thank you. Happy coding.!!

Source Code

The source code for this demo app is on GitHub as an MVVM_Swift repository. You can clone the repo and play with MVVM App.

Flawless iOS

🍏 Community around iOS development, mobile design, and…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store