MVVM with Swift in iOS

In this tutorial we will learn how to Implement MVVM in iOS. First of all let us have a look on what is MVVM design pattern.

MVVM (Model-View-ViewModel)

Model: This is something which is used to hold the data. e.g Model object for Student table.

View: View is responsible to display UI to User.

ViewModel: ViewModel is an intermediate layer between View and Model. ViewModel is responsible for all processing on model and provide required information to view. View is interacting with ViewModel only to get all information.

Problem with MVC (Model-View-Controller):

MVC is also one of major design pattern in iOS but it create problem when code size is increasing. In iOS apple provide single class named ViewController for the operation of View and Controller. So this create issue when user have to perform several operation in same view. It will create massive code in same class file.

Let’s start MVVM Implementation:

In this example we will be converting our existing example to MVVM pattern. Please go through below example before starting:

Above example contains source code as well. This perform following tasks:

  1. Make HTTP call
  2. Parse JSON response
  3. Display in list

So lets start one by one to change same functionality in MVVM pattern:

To display POST data we need to create PostViewModel class first. This class is responsible to interact with Post model class and responsible to provide data to view class whenever their is any change.

PostViewModel class is responsible for:

i) Fetch data from JSON URL.
ii) Notify to view class whenever the data is available OR any change in data.
iii) Provide all required calculation eg. number of rows, height for row etc.
iv) All calculation related work also need to be perform in this class.

ViewModel class trigger the closure whenever the data is available.

Now let’s implement PostViewModel ViewController class:

In above code we just create one object for PostViewModel and call for fetch posts. We also implemented closures to get failure OR success response.

That’s it, Now whenever the response is available, PostViewModel class will notify to view class. Here View controller is working as view class. All view related handling will be maintained by ViewModel class.

You can implement tableview datasource methods in following way:

So in above code you can see that all required information is fetched from ViewModel class. It make code clean and easy to understand.

You can find complete MVVM example here: