The MVVM pattern helps organize your app code by separating data, UI, and logic. This makes your app easier to build and change.
0
0
MVVM pattern in iOS Swift
Introduction
When you want to keep your UI code simple and clean.
When your app has data that changes and you want the UI to update automatically.
When you want to test your app logic without the UI.
When working in a team where designers and developers work separately.
When building apps that need to be easy to maintain and extend.
Syntax
iOS Swift
class ViewModel { var data: String = "" func fetchData() { // load or update data } } class ViewController: UIViewController { var viewModel = ViewModel() override func viewDidLoad() { super.viewDidLoad() viewModel.fetchData() // update UI using viewModel.data } }
The ViewModel holds data and logic.
The ViewController shows UI and talks to ViewModel.
Examples
A simple ViewModel that stores a user name and loads it.
iOS Swift
class UserViewModel { var name: String = "" func loadUser() { name = "Alice" } }
The ViewController uses the ViewModel to get data and update UI.
iOS Swift
class UserViewController: UIViewController { var viewModel = UserViewModel() override func viewDidLoad() { super.viewDidLoad() viewModel.loadUser() print(viewModel.name) // prints "Alice" } }
Sample App
This app shows a number and a button. When you tap the button, the number increases. The ViewModel holds the number and the ViewController updates the screen.
iOS Swift
import UIKit class CounterViewModel { private(set) var count = 0 func increment() { count += 1 } } class CounterViewController: UIViewController { let viewModel = CounterViewModel() let label = UILabel() let button = UIButton(type: .system) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white label.text = "Count: 0" label.textAlignment = .center label.frame = CGRect(x: 50, y: 100, width: 200, height: 50) view.addSubview(label) button.setTitle("Increment", for: .normal) button.frame = CGRect(x: 50, y: 160, width: 200, height: 50) button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) view.addSubview(button) } @objc func buttonTapped() { viewModel.increment() label.text = "Count: \(viewModel.count)" } }
OutputSuccess
Important Notes
MVVM helps keep your UI code simple and your data logic separate.
Use private(set) in ViewModel to protect data from outside changes.
ViewController listens to user actions and updates UI using ViewModel data.
Summary
MVVM splits app code into Model, ViewModel, and View (UI).
ViewModel holds data and logic, View shows UI and talks to ViewModel.
This pattern makes apps easier to build, test, and maintain.