MVC Architecture in Swift


Introduction

MVC (Model-View-Controller) is a design pattern used in Swift to organize code into three separate layers:

  • Model – Manages data and business logic.
  • View – Handles the UI and user interactions.
  • Controller – Acts as an intermediary between Model and View.

Using MVC in Swift ensures better code organization, maintainability, and scalability.

Understanding MVC Components




Model (M)

Represents data and business logic. Does not handle UI or user input.

View (V)

Manages UI elements like labels, buttons, and tables. Does not contain logic to modify data.

Controller (C)

Acts as a bridge between Model and View. Handles user interactions and updates the Model or View accordingly.

Implementing MVC in Swift

Let’s build a basic MVC example where we display user details.

Step 1: Create the Model (Data Layer)

struct User {
     let name: String
     let age: Int
}

✔ Encapsulates data (User details).

Step 2: Create the View (UI Layer)

import UIKit

class UserView: UIView {
     let nameLabel = UILabel()
     let ageLabel = UILabel()

     override init(frame: CGRect) {
         super.init(frame: frame)
         setupView()
     }

     required init?(coder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

     func setupView() {
         nameLabel.frame = CGRect(x: 20, y: 50, width: 200, height: 20)
         ageLabel.frame = CGRect(x: 20, y: 80, width: 200, height: 20)
         self.addSubview(nameLabel)
         self.addSubview(ageLabel)
     }

     func updateView(with user: User) {
         nameLabel.text = "Name: \(user.name)"
         ageLabel.text = "Age: \(user.age)"
     }
}

✔ Displays data but does not modify it.

✔ updateView() updates the UI based on Model data.

Step 3: Create the Controller (Logic Layer)

import UIKit

class UserController: UIViewController {
     let userView = UserView()
     let user = User(name: "John Doe", age: 25)

     override func viewDidLoad() {
         super.viewDidLoad()
         view.backgroundColor = .white
         setupView()
     }

     func setupView() {
         userView.frame = view.bounds
         view.addSubview(userView)
         userView.updateView(with: user)
     }
}

✔ Handles user interactions and updates the view.

✔ Does not contain UI layout code.

Running MVC in a Swift App

To launch the UserController, add the following in SceneDelegate.swift:

window?.rootViewController = UserController()

Output

Name: John Doe
Age: 25

Real-World MVC Example – To-Do List App


Model: ToDoItem.swift

struct ToDoItem {
     let title: String
     var isCompleted: Bool
}

View: ToDoCell.swift

import UIKit

class ToDoCell: UITableViewCell {
     let titleLabel = UILabel()

     func configure(with item: ToDoItem) {
         titleLabel.text = item.title
         accessoryType = item.isCompleted ? .checkmark : .none
     }
}

Controller: ToDoViewController.swift

import UIKit

class ToDoViewController: UITableViewController {
     var items = [
         ToDoItem(title: "Buy groceries", isCompleted: false),
         ToDoItem(title: "Call Mom", isCompleted: true)
     ]

     override func viewDidLoad() {
         super.viewDidLoad()
         tableView.register(ToDoCell.self, forCellReuseIdentifier: "cell")
     }

     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return items.count
     }

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ToDoCell
         cell.configure(with: items[indexPath.row])
         return cell
     }
}

Output

✅ Call Mom
⬜ Buy groceries

✔ Data, UI, and logic are separated using MVC.

Advantages of Using MVC in Swift


  • Better Code Organization – Separates logic, UI, and data.
  • Improved Maintainability – Easy to modify UI without affecting logic.
  • Code Reusability – View and Model can be reused across different controllers.
  • Scalability – Simplifies adding new features.

Conclusion

MVC is a powerful architectural pattern for building structured and maintainable Swift applications. By separating concerns into Model, View, and Controller, Swift apps become easier to scale and maintain.