MVVM in SwiftUI with Sample, A Quick Look

Yasir
3 min readFeb 4, 2021

--

In this article, we will take a very short look at the implementation of MVVM architecture with an example project.

Source Code: GitHub

Introduction

Here you will learn about how UI logic is separated from core application logic by taking your first look at the MVVM architecture pattern. MVVM is a widely used design pattern that allows us to separate core application logic from UI logic.

Model: This is your core model, which will contain all data that you may have consumed from a database or via an external API.

ViewModel: A stripped-down or UI-tailored representation of your Model that contains only the information required for your View.

View: The interface/UI that will be presented to the user and will harness the data from your ViewModel.

MVVM in SwiftUI

Although SwiftUI is provisionally a UI framework, apps being built in SwiftUI will mostly be written in SwiftUI’s syntax, so architecture patterns are just as important.

Observable Objects

Now, we are going to look at observable objects, by observable it mean models that can change state or be updated due to an external API call. For example, a model that houses weather information from a weather API might get updated periodically. We would want our UI to observe this model for any changes and implement updates accordingly.

Let’s imagine a swiftUI project where we are fetching some dummy data from an API and showing it in UI. There will be NetworkManager and PostViewModel and PostModel along with View.

Our PostViewModel will contain the following code :

PostViewModel

The above class PostViewModel is Observable so that our UI can observe the changes. Our class has an init, so wherever we will initialize this model the getPosts function will be called. GetPost function is basically asking that URL for some JSON Data. We have implemented the NetwokMangaer also :

NetworkManager

Now in the PostViewModel , we are creating an array as an article of the type published, so that it will store the information received by that JSON. We are also having a PostResponse struct to math the model as JSON objects :

PostResponse

The array we have created in PostViewModel as articles is another view model called PostModel . PostModel is containing the information of a post that is title and description :

PostModel

Now in order to show information from PostViewModel to our UI, we will create an as model in our UI as below :

ContentView

Where to go from here?

My LinkedIn : linkedin.com/in/my-pro-file

Check This: https://bit.ly/38k4w7l

In order to Get Connected and Read those useful articles, Follow me Here.

--

--

Yasir
Yasir

Written by Yasir

Exploring Swift, SwiftUI, and Apple Universe.

Responses (2)