Swift Academy · Lesson

The MVVM Pattern

Separate view, view model, and model concerns.

Lesson 1 of 413 steps

The MVVM Pattern is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

What Is MVVM?

MVVM stands for Model-View-ViewModel. It is an architectural pattern that separates your app into three layers, each with a single clear responsibility.

  • Model — data and business rules
  • View — what the user sees
  • ViewModel — the bridge that prepares Model data for the View

The goal is separation of concerns: each layer changes for its own reason, independently of the others.

The Model Layer

The Model holds your raw data and the rules that govern it. It knows nothing about the screen or how things are displayed.

Models are usually plain structs or domain objects. They are easy to test because they have no UI dependencies.

struct User {
    let id: UUID
    let firstName: String
    let lastName: String
    let isPremium: Bool
}

struct Order {
    let items: [String]
    let total: Decimal
}

The View Layer

The View is purely presentational. In SwiftUI it is your View structs; in UIKit it is your UIViewController and its subviews.

A good View contains no business logic. It only renders state and forwards user actions to the ViewModel.

struct ProfileView: View {
    @StateObject var viewModel: ProfileViewModel

    var body: some View {
        VStack {
            Text(viewModel.displayName)
            if viewModel.showBadge {
                Text("Premium")
            }
        }
    }
}

The ViewModel Layer

The ViewModel sits between Model and View. It takes raw Model data and transforms it into presentation-ready values the View can show directly.

It also exposes intents (methods) the View calls when the user interacts.

final class ProfileViewModel: ObservableObject {
    @Published var displayName: String
    @Published var showBadge: Bool

    init(user: User) {
        displayName = user.firstName + " " + user.lastName
        showBadge = user.isPremium
    }
}

Why Separate Concerns?

When formatting, networking, and rendering are all tangled inside a view controller, that file becomes a massive, untestable blob.

By splitting responsibilities:

  • The Model can be reused across screens
  • The ViewModel can be unit tested without a UI
  • The View stays small and declarative

What Belongs in the Model

Put in the Model:

  • Domain entities (User, Product)
  • Business validation rules
  • Persistence and networking abstractions (often via services the ViewModel calls)

Never put UI strings, colors, or formatting in the Model.

What Belongs in the ViewModel

The ViewModel handles presentation logic:

  • Formatting dates, currency, and names into display strings
  • Deciding which UI states are visible (loading, error, empty)
  • Coordinating calls to services and exposing results
final class CartViewModel: ObservableObject {
    @Published var totalText: String = ""

    func update(with order: Order) {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        totalText = formatter.string(from: order.total as NSNumber) ?? "-"
    }
}

What Belongs in the View

The View should only:

  • Lay out and render UI elements
  • Read published state from the ViewModel
  • Forward taps and gestures by calling ViewModel methods

If you find an if deciding business rules inside a View, that logic likely belongs in the ViewModel.

Data Flow in MVVM

The flow is one direction for data and the reverse for actions:

  • Model -> ViewModel -> View for data
  • View -> ViewModel for user intents

The View never talks to the Model directly. This keeps dependencies pointing inward toward your domain.

MVVM vs MVC

In classic MVC, the controller often grows huge because it owns formatting, networking, and view wiring all at once.

MVVM extracts that presentation logic into the ViewModel, leaving the controller (or SwiftUI View) thin. The ViewModel is UI-framework agnostic, so it is far easier to test.

A Complete Slice

Here is a small but complete MVVM slice tying the layers together.

struct Account { let balance: Decimal }

final class AccountViewModel: ObservableObject {
    @Published var balanceText: String
    init(account: Account) {
        balanceText = "$" + "\(account.balance)"
    }
}

struct AccountView: View {
    @StateObject var viewModel: AccountViewModel
    var body: some View { Text(viewModel.balanceText) }
}

Quick Check

Test your understanding of MVVM responsibilities.

Recap

You learned the three layers of MVVM and their boundaries:

  • Model — raw data and business rules, no UI
  • ViewModel — presentation logic and intents
  • View — pure rendering of ViewModel state

Keeping these concerns separate makes your code testable, reusable, and easy to reason about. Next we will wire a ViewModel to a View with bindings.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “The MVVM Pattern” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “The MVVM Pattern”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “The MVVM Pattern”?

Separate view, view model, and model concerns. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “The MVVM Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The MVVM Pattern
  2. Binding View Models to Views
  3. The Coordinator Pattern
  4. Testing View Models
← Back to Swift Academy