Coding With Amit
← Back to Articles

MVVM in SwiftUI: A Practical Guide

Amit Sen

iOS engineer and educator. Helping developers build real-world skills.

MVVM in SwiftUI

Model-View-ViewModel is a popular architecture for SwiftUI apps. Here's how to apply it effectively.

The Three Layers

  • Model — Your data and business logic
  • View — SwiftUI views that display data
  • ViewModel — Connects Model and View; holds UI state

A Simple Example

class TodoViewModel: ObservableObject {
    @Published var items: [TodoItem] = []
    
    func addItem(_ title: String) {
        items.append(TodoItem(title: title))
    }
}

struct TodoListView: View {
    @StateObject private var viewModel = TodoViewModel()
    
    var body: some View {
        List(viewModel.items) { item in
            Text(item.title)
        }
    }
}

Best Practices

  1. Keep ViewModels focused on UI state
  2. Use @Published for reactive updates
  3. Inject dependencies (e.g., services) for testability

When to Use MVVM

  • Medium to large apps
  • When you need clear separation of concerns
  • When you want to unit test logic without UI

Ready for more? Check out our SwiftUI Mastery course.