Updated April 5, 2023
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.
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.
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:
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.
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
We hope that this EDUCBA information on “MVVM Swift” was beneficial to you. You can view EDUCBA’s recommended articles for more information.