Dice Foundry Student Workbook

Chapter 13 — Architecture and the View Model

At the end of Chapter 12, Dice Foundry rolls the right dice, keeps a history, saves that history to a file, and has tests for its random-number logic and its storage. The main screen file, ContentView.swift, is still doing too much. It holds the app's data, decides what a roll is, saves the history, and draws every card on the screen. In this chapter you separate those jobs. You move the roll-and-history logic into a new class called RollViewModel, connect the screen to it, and write tests that check the app's behavior without drawing a single view. When you finish, the app looks and behaves the same as before. What changes is where each responsibility lives, and that makes every later change smaller and safer.

This is the most abstract chapter so far, and it comes late on purpose. You now have enough SwiftUI experience to see the problem clearly. Architecture is a response to growth. It makes more sense once you have felt the pain it cures.

Learning Objectives

By the end of this chapter you will be able to:

  • Name the responsibilities that have collected in ContentView and explain why they make the file hard to change and hard to test.
  • Describe the three layers of Dice Foundry (model, view model and view) and what each layer is allowed to do.
  • Explain the difference between a class (a reference type) and a struct (a value type), including what happens when you copy each one.
  • Read and write an @Observable final class with private(set) properties.
  • Explain dependency injection through initializer default values, and why it makes the view model testable.
  • Hold a class instance in @State, and bind a control to one of its properties with $viewModel.selectedDie.
  • Recognize ObservableObject, @Published, @StateObject, @ObservedObject and @EnvironmentObject in older code, and explain how they differ from @Observable.
  • Explain why the test suite is marked @MainActor and what the app target's default actor isolation does.
  • Decide when a view model is worth its extra files, and when a simpler design is the better choice.
  • Move logic into a new class, rewire the view to use it, and run the unit tests.

Concept Explanation

Why ContentView became too large

Open your project from Chapter 12, or the reference file Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/DiceFoundry/ContentView.swift. The file is about 170 lines long. Here is what it owns:

Responsibility Where it lives in Chapter 12 Kind of work
The user's choices: die, quantity, modifier three @State properties input data
The app's results: latest roll, history, roll counter three more @State properties output data
The haptics preference @AppStorage a user setting
The random roller and the history file store two private let properties dependencies
The roll itself: insert, trim, count performRoll() business logic
Clear, load and save the history clearHistory(), loadHistory(), saveHistory() business logic and persistence
Layout: header, cards, history rows, the Roll button body, header, rollButton, historySection, settingsSection presentation

That is three different kinds of work in one struct. Presentation decides how things look. Business logic decides what a roll is and how the history behaves. Persistence decides how data reaches the file. Mixed together, they cause three problems.

Problem one: the rules cannot be tested on their own. The rule "the newest roll goes first, and the history never holds more than 50 rolls" lives inside performRoll(). The Chapter 12 tests check DiceRoller and HistoryStore separately, which is good. But nothing checks the wiring between them, because that wiring lives inside a view. A view's @State values are private to that view, so a test has no direct way to reach them.

Problem two: a change in one place touches everything. To change how history is saved, you edit the same file that decides the colors of the cards and the spacing of the stacks. Each edit risks a mistake in a part of the screen you did not mean to touch.

Problem three: the file does not show its own structure. Six state variables sit at the top of the struct. Nothing tells you which of them the user writes, which the app writes, and which exist only to support the others. A reader has to work that out from the code every time.

Infrastructure Analogy: This is the monolithic script

If you have seen a provisioning script that started as twenty tidy lines and grew into three thousand lines that build servers, configure monitoring, send alerts and write reports, you know this pattern. No single part is wrong. The problem is that every change has a blast radius that covers the whole file. Architecture is the practice of drawing boundaries so that each part has one reason to change.

The three layers

The usual way to draw those boundaries in an app with a screen and some data is to split the code into three layers. Teams use different names, but the roles are stable:

  • Model. The data types and the rules about them. In Dice Foundry these are DieType, RollResult, DiceRoller (which produces random values) and HistoryStore (which saves and loads the file). The model knows nothing about buttons, colors or layout.
  • View model. The object that holds the screen's state and runs its logic. In Dice Foundry this is RollViewModel. It uses the model. It knows nothing about how the screen looks.
  • View. The SwiftUI structs that draw the screen. In Dice Foundry these are ContentView and the components in the Views folder. A view reads state from the view model and sends the user's actions to it.

This arrangement is usually called MVVM, for Model, View and View Model. You do not need to memorize the acronym. The part that matters is one rule:

The view reads and sends. The view model holds state and logic.

In plain terms:

  • A view reads state from the view model so it knows what to draw.
  • A view sends the user's actions to the view model: "roll," "clear the history."
  • The view model holds the state (the current choices, the history) and the logic (how a roll is calculated, when the history is trimmed, when it is saved).
  • The view never calculates a roll and never writes the history file itself.

One exception is deliberate. The picker and the steppers write the user's choices directly into the view model, through bindings. The choices are inputs, and an input has to be writable so that the controls can change it. Later in this section you will see why the results are protected and the choices are not.

Infrastructure Analogy: A controller with a dashboard in front of it

Think of the view model as a controller. It owns the current state and the rules for changing it, and it publishes that state for others to read. The view is the dashboard on top. It renders what the controller reports and forwards the operator's commands back down. The dashboard does not write to the database itself. This comparison is a memory aid, not a formal definition, so do not push it further than that.

Here is the flow of data for the whole app, as you will build it in this chapter:

   ContentView, DiePicker, RollOptionsView, ResultView, HistoryRow
        |                                         ^
        | reads state                             | re-reads when state changes
        | sends roll(), clearHistory()            |
        v                                         |
   RollViewModel   <- the only place where the rules and state live
        |                                         ^
        | roller.roll(...)                        | returns RollResult
        | store.save(...), store.load()           | returns history
        v                                         |
   DiceRoller, HistoryStore, RollResult, DieType   (model)

Keep this picture in mind. Most of the chapter is about making each arrow in the diagram real code.

Classes and structs

RollViewModel is declared as a class. Every custom type you have written so far has been a struct. The difference matters for the rest of your SwiftUI work, so it is worth understanding carefully.

Swift has two kinds of named types that look similar in code:

  • A struct is a value type. When you assign it to a new variable or pass it to a function, Swift makes a copy. Each variable then holds an independent value. Changing one does not change the other.
  • A class is a reference type. When you assign it or pass it, the copies share a single object. Two variables can refer to the same instance, so a change made through one is visible through the other.

The following example is not part of the project. You can type it into a #Playground (Chapter 2) or a scratch file to see the difference for yourself:

Example — not part of the Dice Foundry project
struct CounterValue {
    var count = 0
}

final class CounterObject {
    var count = 0
}

var valueA = CounterValue()
var valueB = valueA
valueB.count = 5
print(valueA.count)

let objectA = CounterObject()
let objectB = objectA
objectB.count = 5
print(objectA.count)
Predict Before You Run: Copies and shared objects

Before you check the answer, predict what each of the two print lines shows. Write both numbers down, and say why. The answers are in Prediction Answers at the end of this chapter.

Why does this matter for SwiftUI? In Chapter 3 you learned that SwiftUI creates and throws away view values constantly. Each time it does, it makes a fresh copy of the ContentView struct. If the view model were a struct, every fresh copy would get its own empty history. A class instance is different: the history can live in one object that every copy of the view refers to. The @State wrapper, which you already know from Chapter 4, keeps that single object alive for as long as the view exists in the hierarchy.

There is a second reason. The @Observable feature that makes SwiftUI notice changes works only on classes. You cannot apply @Observable to a struct. That constraint shapes the design, and you will see it again in the next section.

Note: Why the class is marked final

The keyword final before class means that no other class can inherit from RollViewModel. Inheritance is one of the things classes can do that structs cannot. View models rarely need it, and marking the class final tells every reader (and the compiler) that inheritance is not part of the design. It also allows the compiler to make method calls a little cheaper. Nothing in this course depends on that second point.

@Observable: telling SwiftUI when to read body again

In Chapter 4 you saw that changing a @State value makes SwiftUI read body again. But a class instance held in @State does not change when its properties change. The reference stays the same, so SwiftUI has no signal to act on. The class needs to tell SwiftUI when one of its properties changes. The @Observable macro does that work for you.

A macro is an instruction to the compiler to generate extra code for a declaration. You will not write that generated code, and you do not need to read it in this course. The effect is what matters. The compiler rewrites each stored property of the class so that every read and every write is reported to the Observation framework (the import Observation line at the top of the file). When SwiftUI evaluates a view's body, it records which properties of which objects that body reads. When one of those properties is written, SwiftUI knows exactly which views depend on it, and it re-reads only those bodies.

This is why rollCount is useful. The ResultView depends on rollCount to know when to spin. If the history changes but rollCount does not, the spin does not run. Each view updates when the values it reads change, and not when anything in the class changes.

Here is the minimum you need to write:

Dice Foundry code
@Observable
final class RollViewModel {

Those two lines are the start of the class. You will see them in the Guided Implementation, along with the rest of the class.

Tip: Forgetting @Observable is a silent bug

The code will compile without the @Observable line, because the rest of the class is still valid Swift. The symptom is that the screen does not update after a roll. Chapter 13 Troubleshooting describes how to find that problem quickly.

private(set): readable from outside, writable only inside

The view model's results (the latest roll, the history and the roll counter) are declared with private(set):

Dice Foundry code
private(set) var history: [RollResult] = []

The word private(set) means that other code may read the property, but only code inside the class may change it. The view can display viewModel.history but cannot write viewModel.history = []. The view also cannot call viewModel.history.removeAll(), because that is a change too.

Why does that matter? The rules for changing the history are these: insert the newest roll at the front, trim the list to 50, and then save. If the view could change the list directly, it could skip the trim or skip the save, and nothing would stop it. Keeping the write access inside the class means the rules have exactly one home.

The three choices are different. selectedDie, quantity and modifier are plain var properties with no private(set). The picker and the steppers must write to them through bindings, and a binding that cannot write is useless. The range rules for these choices (the quantity from 1 to 10, the modifier from -20 to 20) are enforced by DiceRoller, which you wrote in Chapter 12, so the view model does not need to check them again. The split is pragmatic. Inputs are writable and outputs are protected. Some teams make inputs read-only too and provide methods such as setQuantity(_:). That is more ceremony than this app needs, and you can make that choice in your own projects.

Dependency injection through initializer defaults

The view model needs two helpers to do its work: a DiceRoller to produce random values, and a HistoryStore to save and load the file. It does not create them itself. It receives them through its initializer:

Dice Foundry code
init(roller: DiceRoller = DiceRoller(), store: HistoryStore = HistoryStore()) {

Passing dependencies from outside is called dependency injection. The class does not reach out to the random number generator or the Documents folder on its own. Something else supplies them. The initializer's parameters have default values, which are the real production helpers. When the app writes RollViewModel(), Swift fills in both defaults, and the app uses the real dice and the real file. When a test writes RollViewModel(roller: ..., store: ...), it supplies fake helpers, and the test controls the outcome.

You met the same idea in Chapter 12 when DiceRoller received a randomValue closure. Dependency injection is that same move applied one level higher: the view model receives the roller and the store, the way the roller receives its random source.

Infrastructure Analogy: Injecting a dependency is like swapping a backend

In infrastructure work you often make a storage backend configurable: a real object store in production, a local directory in a test environment. The code that uses the store does not change. Only the constructor argument does. Dependency injection in Swift works the same way, and the default values are the production configuration.

Consider this example, which is not part of the project:

Example — not part of the Dice Foundry project
let viewModel = RollViewModel()
print(viewModel.latestRoll == nil)
Predict Before You Run: Which helper does the real app use?

Predict which file the first line of the example writes history to, and what the print shows. Then decide what would change if the first line were RollViewModel(store: HistoryStore(fileURL: someTemporaryURL)). Write your answer before you check Prediction Answers. Do not run the example in your real app, because it would change your saved history.

@State holding a class instance

Your new ContentView will hold the view model like this:

Dice Foundry code
@State private var viewModel = RollViewModel()

You already know @State from Chapter 4 as the owner of a small value. Here it owns a reference. @State keeps one RollViewModel alive for as long as the view exists in the hierarchy. Each time SwiftUI creates a new ContentView value, Swift evaluates RollViewModel() again. SwiftUI keeps the first instance it stored and discards the rest. For a small object like this one, that is cheap. If creating the object were expensive, you would keep the work in the initializer small.

Note: Why @State and not a plain property

A plain property (let viewModel = RollViewModel() with no wrapper) would be recreated along with the view struct, and the history would reset every time SwiftUI rebuilt the screen. @State gives the object a lifetime that belongs to the view, which is what you want for a screen-level view model.

Binding to a property of the view model

Inside ContentView, the picker needs a binding to the die choice. You write:

Dice Foundry code
DiePicker(selection: $viewModel.selectedDie)

Read it in two steps. $viewModel is the binding that @State provides for the whole object. Then .selectedDie names one property of that object, and Swift creates a binding to it. Writing through that binding sets viewModel.selectedDie on the shared instance. The picker does not know it is talking to a view model. It only knows it has a Binding<DieType>, which is the same kind of binding you used with @Binding in Chapter 10.

You may see @Bindable in other code. It appears when an observable object is passed to a child view that needs bindings into it. You do not need it in this chapter, because ContentView owns the object in @State.

Older style: ObservableObject, @Published and @StateObject

Much of the SwiftUI code you will find online was written before iOS 17. Before the Observation framework existed, the same job was done with the Combine framework and a set of property wrappers. An older view model typically looks like this. This is a recognition example, and it is not part of the project:

Example — not part of the Dice Foundry project
import Combine

class RollViewModel: ObservableObject {
    @Published var selectedDie: DieType = .d6
    @Published private(set) var history: [RollResult] = []
}

struct ContentView: View {
    @StateObject private var viewModel = RollViewModel()
    // ...
}

Here is how the two styles compare:

Topic Older style (iOS 13 to 16) Dice Foundry (iOS 17 and later)
Declaring the class class X: ObservableObject @Observable final class X
Marking observed properties @Published var on each one plain var (the macro handles it)
Owning the instance in a view @StateObject @State
Receiving an instance from a parent @ObservedObject a plain property (or @Bindable when you need bindings)
Sharing through the environment @EnvironmentObject not used in this course
Update granularity any @Published change notifies the observers of the object SwiftUI tracks the properties each body reads

The key difference is granularity. With ObservableObject, a change to any @Published property tells every view that observes the object that something changed, and those views re-evaluate. With @Observable, SwiftUI knows which properties each view read, so only those views are updated. In a small app you may not notice the difference. In a large app with many views on the same object, you will.

Older code is not wrong. ObservableObject still compiles and runs on iOS 17. Dice Foundry targets iOS 17 because @Observable needs it, so you will use the newer style. When an AI assistant or a tutorial gives you @StateObject and @Published, mentally translate it to the table above before you judge whether the code is correct. If the project's minimum iOS version is 16 or lower, @Observable is not available, and the older style is the right choice.

AI-Assisted Development: Recognize the pattern in generated code

AI assistants often produce ObservableObject code because it dominated the examples they learned from. Such code usually compiles. What you need to check is consistency. A @StateObject on the owner and an @ObservedObject on a child is correct. An @ObservedObject on the owner, which creates a new object every time the view is recreated, is a common bug. When you read generated view-model code, identify who owns the object, then check the wrapper on that property.

Actor isolation at an introductory level

The app target in this project sets a build setting called Default Actor Isolation to MainActor (the exact label may differ slightly in your Xcode). Plain language: by default, all of the app's code runs on the main actor, which is the main thread. SwiftUI reads and updates state on that thread, so keeping your view model there prevents a whole category of timing bugs. You do not need to write @MainActor on RollViewModel, because the project default already applies.

The test target does not have that default. For that reason the test suites in this course are marked @MainActor. In Swift 5 language mode, which this project uses, the compiler does not require the marker, and the tests compile either way. Swift 6 language mode does require it, so the course keeps the marker from the start. You will learn more about concurrency later, when you need it.

When architecture is overkill

Chapters 3 to 9 used one view with its own state, and that was the right design for those chapters. A small screen with a counter and no rules to test does not need a view model. The extra file, the extra class and the extra indirection cost attention, and a two-screen app gains nothing from them.

Dice Foundry crossed the line for three reasons. The file was too large to read in one pass. The most important rule in the app (what goes into the history and in which order) had no tests. And the course will keep adding features, so the cost of a messy file grows with every chapter. A useful rule of thumb: move logic into a view model when you can name a rule that deserves a test, or when a single view has grown too large to read comfortably. Do not create a view model for every view as a reflex. Architecture earns its place by making a specific change easier.

Syntax Breakdown

This section covers the new syntax in Chapter 13 token by token. Syntax from earlier chapters, such as let, var, initializers with self. and for _ in, is used without being explained again.

@Observable and final class RollViewModel {

Token Meaning
@Observable An attribute that asks the compiler to generate observation code for this class's stored properties. It is the Observation framework's version of @Published.
final Forbids subclassing. Nothing may inherit from RollViewModel.
class Declares a reference type. Copies of the variable share one object.
RollViewModel The name, in UpperCamelCase because it is a type.
{ ... } Everything between the braces belongs to the class.

Together: "Declare a reference type named RollViewModel whose stored properties SwiftUI should observe, and which no other class may inherit from."

import Foundation and import Observation

Foundation provides Date, URL, UUID and the JSON coders that RollResult and HistoryStore already use. Observation provides the @Observable attribute. The file does not import SwiftUI. That is deliberate. A view model that does not depend on SwiftUI is easier to test, and it shows that the rules do not depend on the screen.

private let roller: DiceRoller

Token Meaning
private Only code inside RollViewModel can see this property.
let Set once, in the initializer, and never changed afterward.
roller The name of the dependency.
DiceRoller The type from Chapter 12 that produces random values.

init(roller: DiceRoller = DiceRoller(), store: HistoryStore = HistoryStore()) {

Token Meaning
init The initializer. A class does not get an automatic memberwise initializer the way a struct does, so you write it yourself.
roller: An argument label. Callers write roller: ... to pass a value.
DiceRoller The parameter's type.
= DiceRoller() The default value. If the caller omits the argument, Swift creates a real DiceRoller.
store: HistoryStore = HistoryStore() The same pattern for the history store.

Inside the initializer, self.roller = roller copies the parameter into the stored property. The self. is needed because the parameter has the same name as the property. You saw this pattern with custom initializers for structs in Chapter 8.

private(set) var latestRoll: RollResult?

Token Meaning
private(set) Reading is allowed from anywhere that can see the class. Writing is allowed only inside the class.
var A stored property that can change.
latestRoll The name.
RollResult? An optional RollResult. It is nil until the first roll, which is why latestRoll is optional (Chapter 2).

@State private var viewModel = RollViewModel()

Token Meaning
@State Asks SwiftUI to keep this value alive for as long as the view exists.
private Only ContentView uses it.
var viewModel A stored property that can be replaced, which @State requires.
= RollViewModel() The initial value. The type is inferred from the initializer, so no annotation is needed (Chapter 2).

$viewModel.selectedDie

Token Meaning
$viewModel The binding that @State provides for the whole object.
.selectedDie A property of the object. Swift turns it into a binding to that property.

Together: a Binding<DieType> that reads and writes viewModel.selectedDie.

viewModel.latestRoll?.notation (optional chaining, a preview)

The ?. after latestRoll means "if latestRoll has a value, read notation from it; otherwise, the whole expression is nil." It is the short form of an if let check that you already know from Chapter 2. The test file uses it because latestRoll is optional. Chapter 14 returns to optional values when you add a filter.

fileURL: URL? = nil and fileURL ?? URL.temporaryDirectory...

URL? is an optional URL, and = nil makes the parameter optional for callers. Inside the function, ?? is the nil-coalescing operator from Chapter 2. It means "use the left side if it has a value, otherwise use the right side." The test helper uses it to pick a file for the test, or create a unique one.

@MainActor struct RollViewModelTests { and @testable import DiceFoundry

Token Meaning
@MainActor Runs the whole suite on the main actor, which matches how the app runs. Explained in Concept Explanation.
struct A Swift Testing suite is a struct, the same as in Chapter 12.
@testable import DiceFoundry Lets the test target see the app's internal types, such as RollViewModel, without making them public.

DiceRoller(randomValue: { _ in 3 })

The closure { _ in 3 } takes one argument and ignores it (_). It always returns 3. That means every die in the test shows 3, so the results are predictable. Chapter 12 used the same closure for DiceRoller.

for _ in 1...(HistoryStore.maximumCount + 5)

The parentheses make the range 1...55, computed from the sum. _ says that the loop counter is not used. Chapter 6 introduced for ... in and _.

Guided Implementation

Chapter 13 changes two existing files and adds two new ones. Work in this order. The order is chosen so the project builds after every step in Part A, and so you can see each piece work before the next piece depends on it.

Before you begin, check that your project matches Checkpoint 12. Compare your ContentView.swift with Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/DiceFoundry/ContentView.swift. Make sure the project builds with ⌘B. If it does not, fix that first. Chapter 13 assumes the Chapter 12 code is correct.

Warning: The project will not build between Step 6 and Step 11

Part B changes ContentView in several small steps. After Step 6, the view still refers to the old state variables and functions, and the compiler reports errors such as "Cannot find 'selectedDie' in scope" or "Cannot find 'performRoll' in scope." That is expected. Each step after Step 6 removes one group of old references, and Step 11 removes the last ones. Do not run the app until Step 12. If you stop partway through Part B, the project will stay broken until you finish the steps.

Part A: Create RollViewModel

Step 1 — Create the ViewModels folder and RollViewModel.swift

Step 1 — Create the view model file

File: ViewModels/RollViewModel.swift (new) · Where: create a new folder named ViewModels inside the DiceFoundry folder in the navigator, then create the file inside that folder · Action: Create file

In the navigator, right-click the DiceFoundry folder, choose New Folder, and name it ViewModels. Right-click ViewModels, choose New File…, select Swift File, and name it RollViewModel. Make sure the file is created in the DiceFoundry target (the app, not the tests). Replace the file's contents with this code. If Xcode generated its own header comment, you may keep it and replace only the body.

Dice Foundry code
//
//  RollViewModel.swift
//  DiceFoundry
//

import Foundation
import Observation

@Observable
final class RollViewModel {
    // Choices the user is making
    var selectedDie: DieType = .d6
    var quantity: Int = 1
    var modifier: Int = 0

    // Results. Views can read these but only this class can change them.
    private(set) var latestRoll: RollResult?
    private(set) var history: [RollResult] = []
    private(set) var rollCount: Int = 0
}

What it does: declares the class, its three choices and its three results. Every property has a default value, so the class needs no initializer yet.

Why it is written this way: the comments divide the properties into the two groups you read about in the Concept section, inputs that the view writes and outputs that only the class writes. The keywords private(set) enforce the second group.

What should happen: press ⌘B. The build should succeed. Nothing uses RollViewModel yet, so the compiler checks the file but the app does not run it.

Step 2 — Add the dependencies and the initializer

Step 2 — Add the dependencies and init

File: ViewModels/RollViewModel.swift · Where: inside RollViewModel, after the rollCount line and before the class's closing } · Action: Add

Dice Foundry code
    // Dependencies
    private let roller: DiceRoller
    private let store: HistoryStore

    init(roller: DiceRoller = DiceRoller(), store: HistoryStore = HistoryStore()) {
        self.roller = roller
        self.store = store
    }

What it does: stores a DiceRoller and a HistoryStore inside the class, and defines the initializer that receives them.

Why it is written this way: the two properties are let because the class never replaces them after it is created. Without the initializer, the compiler would report that the two constants are never set. The defaults make RollViewModel() create the real helpers, so the app needs no change at its call site. A test can pass fakes.

What should happen: press ⌘B. The build should still succeed.

Step 3 — Add roll() and saveHistory()

Step 3 — Add the roll function and the save helper

File: ViewModels/RollViewModel.swift · Where: inside RollViewModel, after the init you added in Step 2, before the closing } · Action: Add

Dice Foundry code
    func roll() {
        let roll = roller.roll(selectedDie, quantity: quantity, modifier: modifier)
        latestRoll = roll
        rollCount += 1
        history.insert(roll, at: 0)
        if history.count > HistoryStore.maximumCount {
            history.removeLast()
        }
        saveHistory()
    }

    private func saveHistory() {
        do {
            try store.save(history)
        } catch {
            print("Could not save roll history: \(error)")
        }
    }

What it does: calculates a roll from the current choices, records it as the latest roll, increments the counter, inserts it at the front of the history, trims the history to 50, and saves the file.

Why it is written this way: this is the same code that performRoll() and saveHistory() contained in ContentView, moved without change. Only one thing is different: the code now reads selectedDie, quantity and modifier from the class's own properties, not from @State. The local constant roll has the same name as the method roll(). That is legal. Inside the method, the name refers to the local constant, which is the roll result.

saveHistory() is private because nothing outside the class should save the history at a time of its own choosing. Outside code asks for a roll or a clear, and the class decides when to save.

What should happen: press ⌘B. The build should still succeed.

Step 4 — Add clearHistory() and loadHistory()

Step 4 — Add clear and load

File: ViewModels/RollViewModel.swift · Where: inside RollViewModel, after saveHistory(), before the closing } · Action: Add

Dice Foundry code
    func clearHistory() {
        history.removeAll()
        saveHistory()
    }

    func loadHistory() {
        do {
            history = try store.load()
            latestRoll = history.first
        } catch {
            print("Could not load roll history: \(error)")
        }
    }

What it does: clearHistory() empties the list and saves the empty file. loadHistory() reads the file, replaces the history with it, and sets the latest roll to the first item in the list (the newest roll), or nil when the list is empty.

Why it is written this way: clearHistory() calls the same save helper as roll(), so every change to the history goes through one place. loadHistory() is public because the view calls it when the screen appears. It is not called from inside the class. The catch branch prints the error and leaves the current state alone, which is the same error-handling approach you used in Chapter 9.

Notice what clearHistory() does not do. It does not reset latestRoll or rollCount. That is the same behavior as Chapter 12, and it has a visible effect that you will check in Part C.

Note: Clear keeps the latest roll on purpose

clearHistory() changes only history, and then saves the empty list. latestRoll and rollCount stay as they were, so the result card keeps showing the last roll until the app is relaunched and loadHistory() sets latestRoll from the empty list. This is a deliberate design choice in this chapter, kept to match Chapter 12. You will see it in Part C.

What should happen: press ⌘B. The build should succeed. Your RollViewModel.swift file now matches the reference file Reference-Checkpoints/Checkpoint-13-Architecture/DiceFoundry/ViewModels/RollViewModel.swift, except for any difference in the header comment. Open the reference to compare if you want to.

Part B: Connect ContentView to the view model

Each step in this part replaces one group of references in ContentView.swift. Follow the order. The project will not build until Step 11.

Step 5 — Replace the state in ContentView with the view model

Step 5 — Replace the state with the view model

File: ContentView.swift · Where: the top of struct ContentView, from the first @State line down to the roller line, plus the blank line after it · Action: Replace

Before:

Example — not part of the Dice Foundry project
struct ContentView: View {
    @State private var selectedDie: DieType = .d6
    @State private var quantity: Int = 1
    @State private var modifier: Int = 0
    @State private var latestRoll: RollResult?
    @State private var history: [RollResult] = []
    @State private var rollCount: Int = 0

    @AppStorage("hapticsEnabled") private var hapticsEnabled = true

    private let store = HistoryStore()
    private let roller = DiceRoller()

    var body: some View {

After:

Dice Foundry code
struct ContentView: View {
    @State private var viewModel = RollViewModel()

    @AppStorage("hapticsEnabled") private var hapticsEnabled = true

    var body: some View {

What it does: the view no longer holds the choices, the results, the roller or the store. It holds one object, the view model, and that object holds everything else.

Why it is written this way: @State keeps the view model alive for the view's lifetime. The @AppStorage line stays in ContentView, because the haptics preference controls only a visual effect (the vibration), not the roll itself. The preference belongs with the presentation.

What should happen: the project does not build. The compiler now reports that the old names are missing. Continue to Step 6.

Step 6 — Point the picker, the steppers and the result at the view model

Step 6 — Read and write the choices through viewModel

File: ContentView.swift · Where: inside body, in the VStack, the three lines that create DiePicker, RollOptionsView and ResultView · Action: Replace

Before:

Example — not part of the Dice Foundry project
                DiePicker(selection: $selectedDie)
                    .cardStyle()

                RollOptionsView(quantity: $quantity, modifier: $modifier)
                    .cardStyle()

                ResultView(roll: latestRoll, rollCount: rollCount)
                    .cardStyle()

After:

Dice Foundry code
                DiePicker(selection: $viewModel.selectedDie)
                    .cardStyle()

                RollOptionsView(quantity: $viewModel.quantity, modifier: $viewModel.modifier)
                    .cardStyle()

                ResultView(roll: viewModel.latestRoll, rollCount: viewModel.rollCount)
                    .cardStyle()

What it does: the picker and the steppers receive bindings into the view model's choices, so when the user taps a die or changes the quantity, the view model's properties change. The result card receives the latest roll and the counter from the view model.

Why it is written this way: the child views are unchanged. DiePicker and RollOptionsView still take a Binding, just as they did in Chapter 10. The only difference is where the binding points. The $ is still what makes a binding (Chapter 10). The .cardStyle() lines are unchanged because the layout did not change.

What should happen: still no successful build. The remaining errors are in the lines you have not changed yet.

Step 7 — Trigger the haptic and load the history from the view model

Step 7 — Point the haptic trigger and onAppear at viewModel

File: ContentView.swift · Where: after the VStack and its .padding(), in the modifiers of body · Action: Replace

Before:

Example — not part of the Dice Foundry project
        .sensoryFeedback(.impact(weight: .medium), trigger: rollCount) { _, _ in
            hapticsEnabled
        }
        .onAppear {
            loadHistory()
        }

After:

Dice Foundry code
        .sensoryFeedback(.impact(weight: .medium), trigger: viewModel.rollCount) { _, _ in
            hapticsEnabled
        }
        .onAppear {
            viewModel.loadHistory()
        }

What it does: the haptic fires when the view model's roll counter changes. When the screen appears, the view asks the view model to load the saved history.

Why it is written this way: the trigger still reads a changing value, and that value now comes from the view model. The hapticsEnabled closure still belongs to the view, so the condition for the vibration remains in ContentView.

Step 8 — Send the roll and the clear from the buttons

Step 8 — Route the Roll and Clear buttons through viewModel

File: ContentView.swift · Where: the rollButton property (the Roll Dice button), and the Clear button inside historySection · Action: Replace

Before, in rollButton:

Example — not part of the Dice Foundry project
        Button {
            performRoll()
        } label: {

After:

Dice Foundry code
        Button {
            viewModel.roll()
        } label: {

Before, in historySection:

Example — not part of the Dice Foundry project
                Button("Clear") {
                    clearHistory()
                }
                .disabled(history.isEmpty)

After:

Dice Foundry code
                Button("Clear") {
                    viewModel.clearHistory()
                }
                .disabled(viewModel.history.isEmpty)

What it does: tapping Roll Dice calls roll() on the view model. Tapping Clear calls clearHistory() on it. The button is disabled when the view model's history is empty.

Why it is written this way: these closures are the view's way of sending actions. The view names the action and does not know how it is carried out. .disabled reads state from the view model, so the button enables and disables itself as the history changes.

Step 9 — Read the history from the view model

Step 9 — Read the history list from viewModel

File: ContentView.swift · Where: inside historySection, the if that shows "No rolls yet" and the ForEach below it · Action: Replace

Before:

Example — not part of the Dice Foundry project
            if history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            }

            ForEach(history) { roll in
                HistoryRow(roll: roll)
                Divider()
            }

After:

Dice Foundry code
            if viewModel.history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            }

            ForEach(viewModel.history) { roll in
                HistoryRow(roll: roll)
                Divider()
            }

What it does: the history section draws the list that the view model holds. It reads the list. It does not change it.

Why it is written this way: ForEach only reads the array, so it works with a private(set) property. If you tried to change the list here, the compiler would stop you. That protection is what the private(set) keyword is for.

Step 10 — Delete the four old functions from ContentView

Step 10 — Delete the old roll and history functions

File: ContentView.swift · Where: the four private functions after settingsSection, before the closing } of ContentView · Action: Delete

Delete this block completely, including the blank line above it:

Example — not part of the Dice Foundry project
    private func performRoll() {
        let roll = roller.roll(selectedDie, quantity: quantity, modifier: modifier)
        latestRoll = roll
        rollCount += 1
        history.insert(roll, at: 0)
        if history.count > HistoryStore.maximumCount {
            history.removeLast()
        }
        saveHistory()
    }

    private func clearHistory() {
        history.removeAll()
        saveHistory()
    }

    private func loadHistory() {
        do {
            history = try store.load()
            latestRoll = history.first
        } catch {
            print("Could not load roll history: \(error)")
        }
    }

    private func saveHistory() {
        do {
            try store.save(history)
        } catch {
            print("Could not save roll history: \(error)")
        }
    }

What it does: removes the roll logic, the history logic and the persistence logic from the view. The copies that now live in RollViewModel are the only versions.

Why it is written this way: two copies of the same rule would drift apart the first time one was edited. After this step, each rule exists exactly once.

What should happen: press ⌘B. The build should now succeed with no errors and no warnings. ContentView.swift should be about 130 lines long, the same as Reference-Checkpoints/Checkpoint-13-Architecture/DiceFoundry/ContentView.swift. The preview may take a moment to refresh.

Press ⌘B. Confirm the build succeeds before you go on.

Part C: Run the app and check the behavior

Step 11 — Run the app and test the flow

Press ⌘R. The screen should look the same as it did at the end of Chapter 12. Test these behaviors in order:

  1. Tap D8 in the die grid, then press the Number of dice stepper until it shows 3, and tap the Modifier stepper until it shows +2. The selected die should be the one you tapped, and the steppers should show the values you set.
  2. Tap Roll Dice. The result card should show a notation of 3D8 + 2, three dice values, and a total that is 2 more than the subtotal. The history should show one row with the same notation. The haptic should fire if your Simulator and settings allow it.
  3. Tap Roll Dice again. The history should show two rows, and the newest roll should be at the top.
  4. Stop the app with ⌘. and run it again with ⌘R. The history should still show both rows, and the result card should show the newest one. This confirms that loadHistory() runs on launch.
  5. Tap Clear. The history should empty and show "No rolls yet." Stop and run the app again. The history should still be empty.
Predict Before You Run: Roll, roll, then Clear

Before you do step 5 in the Simulator, predict what the result card shows immediately after Clear, before you relaunch the app. Consider what clearHistory() changes and what it leaves alone. Predict the value of rollCount as well. Write down your answers, then check them in the Simulator and in Prediction Answers.

If any step behaves differently, go to Troubleshooting. Do not continue to Part D until the behavior matches the list.

Part D: Test the view model

The tests for RollViewModel run on the test target you created in Chapter 12. They create a view model with a fake roller that always returns 3 and a history file in the temporary folder. They never touch your real history.

Step 12 — Create RollViewModelTests.swift

Step 12 — Create the view model test file

File: DiceFoundryTests/RollViewModelTests.swift (new) · Where: the DiceFoundryTests folder, next to DiceRollerTests.swift · Action: Create file

In the navigator, right-click the DiceFoundryTests folder, choose New File…, select Swift File, and name it RollViewModelTests. In the target membership box, check DiceFoundryTests only. Replace the file's contents with the code below. This first block contains the header, the suite declaration and the helper function. The suite's closing brace comes in Step 14.

Dice Foundry code
//
//  RollViewModelTests.swift
//  DiceFoundryTests
//

import Testing
import Foundation
@testable import DiceFoundry

@MainActor
struct RollViewModelTests {

    // A view model with predictable dice (always 3) and a throwaway history file.
    func makeViewModel(fileURL: URL? = nil) -> RollViewModel {
        let url = fileURL ?? URL.temporaryDirectory.appending(path: "viewmodel-test-\(UUID().uuidString).json")
        return RollViewModel(
            roller: DiceRoller(randomValue: { _ in 3 }),
            store: HistoryStore(fileURL: url)
        )
    }

What it does: imports Swift Testing and the app, and defines a helper that returns a ready-to-use view model. The helper injects the fake roller and a unique file for the history.

Why it is written this way: the helper is the dependency injection you read about in the Concept section, used in a test. Each test gets its own file, so the tests cannot interfere with each other or with the real history.

Step 13 — Add the first two tests

Step 13 — Add the selection and ordering tests

File: DiceFoundryTests/RollViewModelTests.swift · Where: inside RollViewModelTests, after the makeViewModel helper, before the struct's closing brace · Action: Add

Dice Foundry code
    @Test func rollUsesCurrentSelections() {
        let viewModel = makeViewModel()
        viewModel.selectedDie = .d8
        viewModel.quantity = 2
        viewModel.modifier = 5

        viewModel.roll()

        #expect(viewModel.latestRoll?.notation == "2D8 + 5")
        #expect(viewModel.latestRoll?.total == 11)
        #expect(viewModel.rollCount == 1)
    }

    @Test func newestRollIsFirstInHistory() {
        let viewModel = makeViewModel()
        viewModel.selectedDie = .d4
        viewModel.roll()
        viewModel.selectedDie = .d12
        viewModel.roll()

        #expect(viewModel.history.count == 2)
        #expect(viewModel.history.first?.dieType == .d12)
        #expect(viewModel.history.last?.dieType == .d4)
    }

What it does: the first test checks that a roll uses the choices stored in the view model, and that the result has the expected notation and total: two D8 dice with 3 each, plus 5, makes 11. The second test checks that the newest roll goes to the front of the history.

Why it is written this way: each test sets up the state it needs, performs one action, and checks the result with #expect. The fake roller always returns 3, so the expected values are known. These tests check the rules that were impossible to test while they lived inside ContentView.

Step 14 — Add the remaining three tests and close the suite

Step 14 — Add the cap, clear and persistence tests

File: DiceFoundryTests/RollViewModelTests.swift · Where: inside RollViewModelTests, after newestRollIsFirstInHistory(), then the struct's final closing } · Action: Add

Dice Foundry code
    @Test func historyNeverExceedsMaximum() {
        let viewModel = makeViewModel()
        for _ in 1...(HistoryStore.maximumCount + 5) {
            viewModel.roll()
        }
        #expect(viewModel.history.count == HistoryStore.maximumCount)
    }

    @Test func clearHistoryEmptiesTheList() {
        let viewModel = makeViewModel()
        viewModel.roll()
        viewModel.clearHistory()
        #expect(viewModel.history.isEmpty)
    }

    @Test func historySurvivesANewViewModel() {
        let url = URL.temporaryDirectory.appending(path: "relaunch-test-\(UUID().uuidString).json")

        let firstLaunch = makeViewModel(fileURL: url)
        firstLaunch.roll()
        firstLaunch.roll()

        let secondLaunch = makeViewModel(fileURL: url)
        secondLaunch.loadHistory()

        #expect(secondLaunch.history.count == 2)
        #expect(secondLaunch.latestRoll?.id == firstLaunch.history.first?.id)
    }
}

What it does: the first test rolls 55 times and checks that the history holds only 50. The second checks that clearing empties the list. The third simulates a relaunch: it creates one view model, rolls twice, then creates a second view model that points at the same file, loads it, and checks that the two rolls are back.

Why it is written this way: the third test is the test-suite version of closing and reopening the app. Both view models point at the same file, so the second one reads what the first one saved. The closing } ends the struct. Without it, the file will not compile.

Step 15 — Run the tests

Press ⌘U. Xcode builds the app and the tests, then runs the whole test target. Open the Test navigator (⌘6) if it is not showing. You should see a RollViewModelTests group with the five tests in it, and the Chapter 12 suites should still pass. If any test fails, read its message in the report and go to Troubleshooting.

Running the tests is the first time you check the view model without the Simulator. A passing historyNeverExceedsMaximum test proves the rule that the history never grows past 50, and it does so in a fraction of a second, without rolling 55 times by hand.

Expected Results

Warning: Teaching simplification: persistence errors are console-only

The guided app and final solution print load and save errors to Xcode's console; they do not show a failure message in the app. A failed save leaves the new history visible in memory, so the screen is not proof that it reached disk. Relaunching can restore older data. A failed load leaves history unavailable, and the next successful save can replace the unreadable file. This is enough to practice throws and catch, but it is not production-ready error handling. Before shipping, show a visible error state, offer an appropriate retry or recovery path, and preserve unreadable saved data before replacing it. Chapter 9's optional load-error-message challenge is a first step; it does not cover save failures.

After Part C, the screen should look and behave like the Chapter 12 version. The layout, the cards, the haptic and the Dark Mode appearance have not changed, because the presentation code did not change. The only changes are internal: where the rules live and how the tests check them.

Here is the screen in Dark Mode with some rolls in the history:

Actual iOS Simulator screenshot — Dice Foundry at the end of Chapter 13 in Dark Mode

After Part D, ⌘U should report that the new RollViewModelTests suite and its five tests pass, alongside the tests from Chapter 12. The test navigator should show a green check next to each one.

Illustrative mockup — not a screenshot. This sketch shows the layout of the view tree after this chapter. It does not show new visuals:

Illustrative mockup — not a screenshot

ContentView   (reads viewModel; owns it in @State; owns @AppStorage)
  ScrollView
    VStack
      header
      DiePicker         ($viewModel.selectedDie)
      RollOptionsView   ($viewModel.quantity, $viewModel.modifier)
      ResultView        (viewModel.latestRoll, viewModel.rollCount)
      historySection    (viewModel.history)
      settingsSection   (@AppStorage hapticsEnabled)
  safeAreaInset: Roll Dice button  -> viewModel.roll()

The reference for this checkpoint is Reference-Checkpoints/Checkpoint-13-Architecture/. The Simulator shows the behavior described here. To run on your own iPhone, see Optional Device Lesson D1; the course author has not tested that on hardware.

Reading This Like a Developer

This section traces the code that now runs when you tap Roll Dice. Read the trace once slowly, then read it again while you look at the code. The goal is to be able to answer the same questions about any screen you open.

Where execution begins. The app still starts at @main in DiceFoundryApp.swift. Its WindowGroup creates ContentView(). Nothing about the start-up path changed in this chapter. The new part is that ContentView's @State property creates a RollViewModel the first time the view appears.

What runs when you tap Roll Dice. Follow the arrows:

1. You tap "Roll Dice"
   -> the Button's closure runs:  viewModel.roll()          (ContentView)
2. roll() reads selectedDie, quantity and modifier          (RollViewModel)
   -> roller.roll(...) returns a new RollResult             (DiceRoller)
3. latestRoll = roll          (a write to a private(set) property)
4. rollCount += 1             (a write that the haptic and ResultView observe)
5. history.insert(roll, at: 0) and trim to 50               (RollViewModel)
6. saveHistory() -> store.save(history)                     (HistoryStore)
   -> the JSON is written to roll-history.json
7. SwiftUI sees the writes made to properties the views read
   -> ContentView.body is evaluated again
   -> ResultView receives the new roll and a new rollCount
   -> ResultView's onChange(of: rollCount) runs spin()
   -> the history list is rebuilt from viewModel.history
   -> the sensoryFeedback trigger changes, so the haptic may fire

Step 7 is the key to the whole architecture. The view model does not call the view. It changes its own properties, and SwiftUI finds the views that read those properties. Because ContentView.body reads latestRoll, history and rollCount, those changes reach it. Each child view then updates from its own parameters.

Which variables hold state. There are two kinds of state. The choices (selectedDie, quantity, modifier) live in RollViewModel, and the picker and steppers write them through bindings. The results (latestRoll, history, rollCount) also live in RollViewModel, and only the class writes them. The haptics preference lives in ContentView, in @AppStorage, because it belongs to presentation. ResultView also keeps its own rotation value in @State, because the spin angle is purely visual.

Where a value originates and where it changes. Every roll is created in DiceRoller.roll(...), from random numbers that Int.random(in:) supplies in the app. The value is first stored in latestRoll, then copied into history at the front of the array. On the next launch, loadHistory() reads the saved values back and sets latestRoll from the first item.

Where data is saved. Only saveHistory() writes to the file, and only RollViewModel calls it. That call happens after every roll and every clear, and it is the one place where the file's contents are decided.

How errors are handled. saveHistory() and loadHistory() catch their errors and print a message. They do not show an alert, and they do not stop the app. The user sees an empty or partial history, and the console shows the cause. That is a deliberate choice for this app. A production app would show a message to the user, and you can add that later.

Business logic versus presentation logic. This is the question the chapter was about. Business logic is in RollViewModel and in the model types it calls: how a roll is calculated, which rolls are kept, when the history is saved. Presentation logic is in the views: which color a card uses, how big a circle is, whether a button is disabled, whether a haptic fires. A change to the look of the app should never require a change to the rules, and a change to the rules should never require touching the look.

Reading This Like a Developer: Read the button, then find the property

When you read an unfamiliar SwiftUI screen, start at a button and follow its closure. If the closure calls a method on a view model, open that class and read the method. Then find every property the method writes. Those properties are the state, and the views that read them are the ones that change.

Troubleshooting

The screen does not update after a roll

Symptoms: you tap Roll Dice and nothing changes on screen, but the next launch shows the new roll in the history.

What it means: the data is changing, but SwiftUI is not told about the change. The view model is not being observed.

Likely causes:

  • The @Observable line is missing or misspelled above final class RollViewModel. The class still compiles, so you will not get a build error.
  • The class was changed to a struct. The @Observable macro works only on classes.

How to investigate: open RollViewModel.swift and check the first lines of the class declaration. Make sure @Observable is on the line immediately above final class RollViewModel {, and that the keyword is class. Then run the app again.

A message similar to "Cannot find 'selectedDie' in scope" or "Cannot find 'performRoll' in scope"

What it means: ContentView.swift still refers to a name that was removed in Step 5 or Step 10.

Likely causes: a step was skipped, or a block was pasted over the wrong lines.

How to investigate: click the error in the issue navigator (⌘5) and read the line number. If the line uses a bare name such as selectedDie, history or performRoll, add viewModel. in front of it, or delete the old function if it is one of the four removed in Step 10. Compare the finished file with the reference.

A message similar to "Cannot find type 'RollViewModel' in scope"

What it means: the compiler cannot find the class. Usually the file is not in the target, or it was created in the wrong folder.

Likely causes: RollViewModel.swift is not a member of the DiceFoundry target, or the file is named differently from the class.

How to investigate: click RollViewModel.swift in the navigator and open the File Inspector (⌥⌘1). Under Target Membership, the DiceFoundry box should be checked. Then build again.

A message similar to "Cannot assign to property: 'latestRoll' setter is inaccessible"

What it means: something outside RollViewModel tried to write to a private(set) property. The compiler stopped it on purpose.

Likely causes: code in ContentView such as viewModel.latestRoll = nil, or viewModel.history.removeAll(). Writes belong in the view model's own methods.

How to investigate: read the line the error points to. Replace the write with a call to a method on the view model, such as viewModel.clearHistory(). If you think a new action needs to change the state, add a method to RollViewModel instead of relaxing the protection.

A message similar to "No such module 'Testing'" in RollViewModelTests.swift

What it means: the test file is in the app target, not the test target. The app target cannot import the Swift Testing framework.

Likely causes: the file was created while the app target was selected, or the target membership box was not changed.

How to investigate: select RollViewModelTests.swift, open the File Inspector (⌥⌘1), and make sure only DiceFoundryTests is checked under Target Membership. Uncheck DiceFoundry if it is checked.

A message similar to "Cannot find 'RollViewModel' in scope" in the test file

What it means: the test file cannot see the app's internal types.

Likely causes: the @testable import DiceFoundry line is missing or misspelled. Without it, the test target sees only public declarations, and RollViewModel is internal.

How to investigate: check the first imports in the file. Both import Testing and @testable import DiceFoundry should be present.

A test fails, but the app appears to work

What it means: the rule in the test is not what the app does, or the app does something you did not intend.

Likely causes: a typo in an expected value, a missing saveHistory() call (the second launch test would fail), or a change to the trim logic.

How to investigate: read the failure message in the Test navigator. Compare the expected and actual values. Run the rule by hand in the Simulator, or add a print line temporarily to see the values. Remember that historySurvivesANewViewModel depends on the file, so a leftover file from an earlier run should not matter, because each test uses a new file name.

The history is empty after a relaunch

What it means: loadHistory() did not run, or the file could not be read.

Likely causes: the .onAppear modifier in ContentView still calls the old loadHistory() (which no longer exists), or the catch branch printed an error.

How to investigate: check the .onAppear closure, which must call viewModel.loadHistory(). Then open the debug console (⇧⌘Y) and look for a message beginning "Could not load roll history." That message comes from the catch branch, and it includes the cause.

Knowledge Check

  1. Name the three kinds of work that were mixed together in Chapter 12's ContentView. For each one, say which layer of the new design it moves to.
  2. Why is RollViewModel a class rather than a struct? What would happen to the history if you assigned an instance to a second variable and then changed the copy?
  3. A teammate adds viewModel.history.removeAll() in the Clear button's closure and reports a compile error. Explain why the compiler stops the code, and say where the logic belongs instead.
  4. The haptics preference is still stored in ContentView with @AppStorage. Explain why it stays there rather than moving into RollViewModel.
  5. You find an older project that uses ObservableObject, @Published and @StateObject. Is the code wrong on iOS 17? Describe the changes you would make to bring it to the style used in this chapter, and name one difference in how the two styles update the screen.

Independent Challenge

Important: Commit before branching and switching

Before creating a challenge branch, run this chapter's Development Checkpoint on main to commit and tag the guided work. Confirm git status --short prints nothing. After the challenge, commit your practice edits on the challenge branch before switching back to main; uncommitted edits can follow you across branches. If no files changed, no extra commit is needed. The guided checkpoint is already saved, so skip its commit and tag commands when you reach that section again.

Do this challenge on a Git branch so that the guided project stays identical to the reference checkpoint. Progressive hints are in ch13-exercises.md. A full solution is in ch13-answers.md.

Challenge: Challenge 1 — Reset the choices, not the history

Add a way to reset the user's choices to their starting values without touching the history. Put the logic in the view model, and put only a button in the view.

Requirements:

  • Add a method resetChoices() to RollViewModel. It sets selectedDie to .d6, quantity to 1, and modifier to 0. It does not change history, latestRoll or rollCount.
  • In ContentView, add a button labeled Reset choices to the settings card, below the haptic toggle. Its action calls viewModel.resetChoices(). To place the button below the toggle, wrap the toggle and the button in a VStack with alignment: .leading and spacing: 12.
  • Add a test named resetChoicesKeepsHistory to RollViewModelTests. It rolls once, changes the choices, calls resetChoices(), and checks that the choices are back to their starting values and the history still has one item.

Acceptance criteria:

  • The rule for resetting is in RollViewModel, not in ContentView.
  • Tapping Reset choices returns the die picker to D6 and the steppers to 1 and +0, and the history rows stay exactly as they were.
  • The new test passes with ⌘U, along with the existing tests.
  • The project builds with no errors and no warnings.

Create the branch with git switch -c challenge-13, and return to the guided project with git switch main before you start Chapter 14.

Chapter Completion Checklist

  • I can name the three responsibilities that were mixed in ContentView and where each one lives now.
  • I can explain the difference between a class and a struct, and why RollViewModel is a class.
  • I created ViewModels/RollViewModel.swift in the DiceFoundry target, with the @Observable final class declaration, the choices, the private(set) results, the dependencies and the initializer.
  • RollViewModel contains roll(), clearHistory(), loadHistory() and the private saveHistory().
  • ContentView holds @State private var viewModel = RollViewModel() and keeps @AppStorage for the haptics preference.
  • ContentView no longer contains performRoll(), clearHistory(), loadHistory() or saveHistory().
  • The project builds with no errors and no warnings.
  • The app runs, and the history survives a relaunch and a Clear behaves as described in Part C.
  • RollViewModelTests.swift is in the DiceFoundryTests target, and ⌘U runs its five tests.
  • I can explain why private(set) protects the results but not the choices.
  • I can recognize ObservableObject, @Published, @StateObject and @ObservedObject, and I know which iOS version each style needs.

Development Checkpoint

Save this chapter as a Git commit and tag it, the same way you did in earlier chapters.

In Xcode, choose Integrate → Commit... (or Source Control → Commit... in some versions). Check that the changed files include ContentView.swift, the new ViewModels/RollViewModel.swift and the new DiceFoundryTests/RollViewModelTests.swift. Enter the message Chapter 13: Architecture and the view model and commit.

Or in Terminal, from your project folder:

git add -A
git commit -m "Chapter 13: Architecture and the view model"
git tag chapter-13

To compare your project with the reference, run this from the folder that contains both your project and the course's Reference-Checkpoints folder. Replace the paths with your own:

diff -r Reference-Checkpoints/Checkpoint-13-Architecture/DiceFoundry ~/Documents/DiceFoundryCourse/DiceFoundry/DiceFoundry

The Swift files should match the reference, except for header comments and whitespace. Differences in ContentView.swift are worth understanding before you move on. Chapter 14 builds on the view model, so the code you wrote in this chapter is the starting point for the next one.

Prediction Answers

Copies and shared objects. The first print shows 0. valueB is a copy of valueA, so changing valueB.count does not affect valueA. The second print shows 5. objectB and objectA refer to the same instance, so changing objectB.count changes what objectA sees. This is the reason the view model is a class: SwiftUI keeps one instance that every copy of the view refers to.

Which helper does the real app use? RollViewModel() with no arguments uses the default HistoryStore(), which points at roll-history.json in the app's Documents folder. The print shows true: nothing has been rolled, so latestRoll is nil. If the call were RollViewModel(store: HistoryStore(fileURL: someTemporaryURL)), the default store would be replaced, and the history would go to the temporary file. The roller would still be the default DiceRoller(), because only the store argument changed. That is dependency injection: each argument can be replaced separately.

Roll, roll, then Clear. Immediately after Clear, the history is empty and the Clear button is disabled. The result card still shows the most recent roll, because clearHistory() changes only history and then saves. latestRoll is not reset. rollCount is 2, because it counts rolls, and clearing does not undo them. After you relaunch the app, loadHistory() reads the empty file and sets latestRoll to history.first, which is nil. The card then returns to its empty state. This difference between the screen before and after a relaunch is a real behavior of the code in this chapter. It is not a crash, and Chapter 14 is a good place to decide whether it should change.

Roll with a quantity of 99. This prediction is about the layers, and the example is for thinking only; do not type it into the app. Setting viewModel.quantity = 99 is allowed, because quantity is a plain var. When you call roll(), the view model passes 99 to DiceRoller, which clamps the value to the range 1 to 10 (Chapter 12). The result has 10 values and the notation 10D6, not 99D6. The rule for the range lives in DiceRoller, which is why the view model does not need to check it. The stepper in the app cannot produce 99, because its own range stops at 10.