MVVM in SwiftUI with Sample, A Quick Look

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

Source Code: GitHub


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

Observable Objects

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 :


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 :


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 :


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 :


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


Where to go from here?

My LinkedIn :

Check This:

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