EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Swift Tutorial MVVM Swift
Secondary Sidebar
Swift Tutorial
  • Basics
    • How To Install Swift?
    • Swift Version
    • Swift Package Manager
    • Swift Operators
    • Swift Loop
    • Swift For Loop
    • Swift while loop
    • Swift do-while
    • Swift array
    • Swift Queue
    • Swift Dictionary
    • Swift forms
    • Swift sets
    • Swift map
    • Swift int to string
    • Swift Interview Questions
    • Swift extension
    • Swift guard
    • Swift enum
    • Swift zip
    • Swift?hashable
    • MVVM Swift

MVVM Swift

MVVM Swift

Introduction to MVVM Swift

MVVM Swift is the advanced version of the MVC Architecture Pattern. It introduces the (fourth) component called View Model. The View Model is dependable for controlling the model and focusing the model’s data on outlook through the controller. MVVM Swift includes the four major components: Model, View, View Model, and Controller. Each component has its individual job, and they joined together to provide the structure to the application.

What is MVVM Swift?

MVVM Architectural Pattern enables us to make the project structural and simple to manage, so it is easy for the developers to search out the files and control them.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The MVVM contains three components, they are:

  • Model: It holds the data. It is also liable for symbolizing data from business logic, and this model layer does not know about any other layers.
  • View: It is the representation of UI. This layer is liable for handling entire layouts and viewing the data inaccessible way. The View can able to know about the ViewModel, but it does not know about the Model.
  • View Model: It holds the business logic, and the controller acts as the intermediary between model and view. ViewModel is used to transform the data retrieved in the View method, works with the business logic, and retrieves the actions from the View. Each component has its individual job, and they joined together to provide the structure to the application. This is the separation of concerns of the application, which helps in testing and further maintenance purpose.

MVVM Swift 1

How to Use MVVM Swift?

This Pattern is used to transform the data from the model class to the representation, which works for several views. ViewModel transforms the String to NSAttriburedString or formatted string Date. This pattern is related to MVC; we are required to include the ViewModel Classes in the existing Codebase and represent the data as you require. It minimizes the View Controller’s role, which helps reduce the View Controller Classes.

Let’s see how MVVM works in code:

1. To Create the New Swift Project

Just create the folder structure of entire components like Model-ViewController-ViewModel and then move on to the coding part.

Initially, the Model Class is to be defined, and for storing the data in the model we have to create the Model.

Code:

struct DataModel: Codable {
var data:QuesModel?
}
struct QuesModel: Codable {
var Newquestions: [NewQuestions]?
}
struct NewQuestions: Codable {
var ct_answer: String?
var answer_1: String?
var answer _2: String?
var answer _3: String?
var answer _4: String?
var topquestion: String?
}

2. To Call API and Fill Data Model

Once we make a call to API, the Model will get loaded so that we can right use the Model in ViewController for loading purposes in the view.

Code:

class QuesViewModel {
var quesData:DataModel?
private let sourcesURL = URL(string: "https://quiz-68112-default-rtdb.firebaseio.com/quiz.json")!
func apiToGetQuesData(completion : @escaping () -> ()) {
URLSession.shared.dataTask(with: sourcesURL) { [weak self] (data, urlResponse, error) in
if let data = data {
    let jsonDecoder = JSONDecoder()
    let empData = try! jsonDecoder.decode(DataModel.self, from: data)
    self?.quesData = empData
    completion()
}
}.resume()
}
}

3. To Update View Controller

To get the data into ViewModel Class to update ViewController with data this got in ViewModel. To design UITableView on screen and then to load the questions required data to table View, which we got in the ViewModel.

Code:

class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var viewModel = QuesViewModel()
var quesi:DataModel?
override func viewCheckLoad() {
super.viewCheckLoad()
viewModel.apiToGetQuesData { [weak self] in
self?.quesi = self?.viewModel.quesData
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
quesi?.data?.ques?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = quesi?.data?.ques?[indexPath.row].ques
return cell
}
}

MVVM Swift Project Structure

The View Model is dependable for controlling the model and focusing the model’s data on the outlook through the controller.

Let’s see the structure of the project as follows:

structure of project

The above diagram explains the structure of the MVVM Project:

  • Configs: The application environment settings like development configurations, production, and staging are entirely using the .xcconfig files.
  • Coordinators: The coordinator Pattern is mostly used nowadays. It helps in separating the navigation logic by eliminating the controllers.
  • Core: In essence, it is for AppDelegate.
  • Models: It is the Model where it maintains the entire Model Objects from API.
  • Resources: In this resources file, the project assets launch the storyboard.
  • Services: This Service contains the CoreData, API Service, UserDefaults, and so on.
  • Utils: The utils contain the helper files like custom errors and extensions.
  • View: In View, it stores the components of View like Custom Views, Cells, buttons, and so on.
  • ViewController: It contains the UI-related code. It does not have any business logic in it. The View Part of MVVM uses the name appropriate to the UIViewControllers element from iOS.

MVVM Swift Design Pattern

The Design Pattern is extremely very useful that is not required any language to perform it is just the platform we developed for each and every developer must know how and when to apply them. Here we going to see the process as follows. MVVM Swift is the advanced version of the MVC Architecture Pattern. It contains the components in it.

The MVVM (Model-View-ViewModel) is the structural design pattern that separates the objects into three components.

They are as follows:

  • Models hold the application data mostly; it will be simple classes or structs.
  • Views are visual elements that control on screen. It is subclasses of UI View. The view is used to display the visual elements.
  • ViewModels are the transformed data method into the values displayed on the view. It will be usually classes so that it can be passed as references.

MVVM Swift 3

The above images are similar to the MVC (Model-View-Controller) Pattern.

Conclusion

In this article, we have seen about the new concept MVVM, which is the View Model is reliable for controlling the model and focusing the model’s data to outlook through the controller.

Recommended Articles

This is a guide to MVVM Swift. Here we discuss the introduction, and how to use MVVM swift? project structure and design pattern, respectively. You may also have a look at the following articles to learn more –

  1. Swift hashable
  2. Swift enum
  3. Swift extension
  4. Swift int to string
Popular Course in this category
Swift Training (10 Courses, 11+ Projects)
  10 Online Courses |  11 Hands-on Projects |  63+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Windows Forms Training (4 Courses, 3+ Projects)4.9
Kali Linux Training (3 Courses, 3+ Projects)4.8
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more