Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Model-View-ViewModel (MVVM) Tutorial

Introduction to MVVM

The Model-View-ViewModel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface from the business logic or back-end logic (the data model). This pattern is particularly useful in iOS development, especially when using SwiftUI.

Components of MVVM

MVVM consists of three main components:

  • Model: Represents the data and the business logic of the application. It directly manages the data, logic, and rules of the application.
  • View: Represents the UI of the application. It displays the data and sends user actions (e.g., clicks, text input) to the ViewModel.
  • ViewModel: Acts as an intermediary between the View and the Model. It retrieves data from the Model and formats it for display in the View. It also processes user input from the View and updates the Model accordingly.

Setting Up an MVVM Project in iOS

Let's create a simple MVVM project in iOS using Swift.

1. Open Xcode and create a new SwiftUI project.

2. Create new files for Model, View, and ViewModel.

Example: Simple MVVM App

We will create a simple app that displays a list of items using MVVM.

Model

The Model is responsible for representing the data.

// ItemModel.swift
struct Item: Identifiable {
    var id = UUID()
    var name: String
}
                

ViewModel

The ViewModel provides data to the View and handles user interactions.

// ItemViewModel.swift
import Combine

class ItemViewModel: ObservableObject {
    @Published var items: [Item] = []

    init() {
        fetchItems()
    }

    func fetchItems() {
        self.items = [
            Item(name: "Item 1"),
            Item(name: "Item 2"),
            Item(name: "Item 3")
        ]
    }
}
                

View

The View displays the data provided by the ViewModel.

// ContentView.swift
import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel = ItemViewModel()

    var body: some View {
        NavigationView {
            List(viewModel.items) { item in
                Text(item.name)
            }
            .navigationBarTitle("Items")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
                

Conclusion

In this tutorial, we learned about the MVVM architectural pattern and how to implement it in an iOS application using SwiftUI. By separating the UI code from the business logic, MVVM makes our codebase more maintainable and testable. Happy coding!