Chapter 13 Answers — Architecture and the View Model
Knowledge Check Answers
1. What were the three kinds of work mixed in Chapter 12's ContentView, and where do they go now?
The three kinds are presentation (how things look), business logic (how a roll is calculated, how the history behaves) and persistence (saving and loading the file). Presentation stays in the views: ContentView, DiePicker, RollOptionsView, ResultView and HistoryRow. Business logic moves into RollViewModel, which calls the model types DiceRoller and RollResult. Persistence is handled by HistoryStore, which RollViewModel calls when it saves and loads. The haptics preference is an exception: it is presentation, so it stays in ContentView with @AppStorage.
2. Why is RollViewModel a class rather than a struct? What happens if you copy an instance?
Two reasons. First, a struct would be copied each time SwiftUI rebuilds the view, and each copy would start with its own history. A class instance is shared, so @State can keep one object alive for the view's lifetime. Second, the @Observable macro works only on classes. If you assign an instance to a second variable, both variables refer to the same object. A change made through the copy is visible through the original, because there is only one history. That is the opposite of a struct, where copying creates an independent value.
3. A teammate adds viewModel.history.removeAll() to the Clear button and gets a compile error. Why, and where should the logic live?
history is declared private(set), so code outside RollViewModel can read it but cannot change it. removeAll() changes the array, so the compiler refuses. The rule for clearing includes saving the empty file, and that rule belongs in the view model. The button should call viewModel.clearHistory(), which removes the items and calls the save helper. The protection exists so that no other code can skip the save.
4. Why does the haptics preference stay in ContentView with @AppStorage?
The haptic is a visual and tactile effect, and .sensoryFeedback belongs to the view. The preference is read only to decide whether that effect plays. The view model does not need to know about vibration, so keeping the preference in the view keeps the view model free of user-interface concerns. If a second screen later needed the same preference, you could move it to a shared place, but this app does not need that yet.
5. An older project uses ObservableObject, @Published and @StateObject. Is it wrong on iOS 17? What would you change, and how does the update behavior differ?
It is not wrong. ObservableObject still compiles and runs on iOS 17. To modernize it: change class X: ObservableObject to @Observable final class X, remove @Published from each property (keep var, and keep private(set) where needed), change @StateObject in the owning view to @State, and change @ObservedObject in child views to a plain property (or @Bindable where a child needs bindings). On update behavior: with ObservableObject, a change to any @Published property notifies every observer of the object, so views that observe it are asked to re-evaluate. With @Observable, SwiftUI records which properties each view's body reads, so only the views that read a changed property are updated.
Independent Challenge Solution
Challenge 1 — Reset the choices, not the history
Solution folder: challenge-solutions/ch13-reset-choices/
The folder holds a copy of Checkpoint-13-Architecture with the three changes below applied. Compare it with the reference with diff -r to see exactly what changed.
Verification status: Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The verification run reported OK errors=0 warnings=0 test cases passed=46 failed=0 (both simulators) for this folder. The 46 results are 17 plain tests run once on each of two simulators (34), plus a parameterized test that runs six times on each simulator (12). All tests passed on both simulators.
Step 1 — Add the rule to RollViewModel. In ViewModels/RollViewModel.swift, add this method after clearHistory(), inside the class:
func resetChoices() {
selectedDie = .d6
quantity = 1
modifier = 0
}
Why it works: the three choices are the only state the method changes. It does not call saveHistory(), and it does not touch history, latestRoll or rollCount, so the history survives. The method lives in the view model, so the rule has one home, and a test can call it without any view.
Step 2 — Add the button to ContentView. In ContentView.swift, replace settingsSection with this version. The toggle is unchanged, and the button is added below it inside a VStack:
private var settingsSection: some View {
VStack(alignment: .leading, spacing: 12) {
Toggle(isOn: $hapticsEnabled) {
Label("Haptic feedback", systemImage: "iphone.radiowaves.left.and.right")
}
Button("Reset choices") {
viewModel.resetChoices()
}
}
}
Why it works: the button's closure only sends the action. The VStack with alignment: .leading places the two controls in a column at the left edge, matching the other cards, and spacing: 12 matches the spacing used in RollOptionsView.
Step 3 — Add the test. In DiceFoundryTests/RollViewModelTests.swift, add this test before historySurvivesANewViewModel():
@Test func resetChoicesKeepsHistory() {
let viewModel = makeViewModel()
viewModel.roll()
viewModel.selectedDie = .d20
viewModel.quantity = 4
viewModel.modifier = -3
viewModel.resetChoices()
#expect(viewModel.selectedDie == .d6)
#expect(viewModel.quantity == 1)
#expect(viewModel.modifier == 0)
#expect(viewModel.history.count == 1)
}
Why it works: the test sets all three choices to values that are not the defaults, so the reset has something to change. It checks the choices and the history count. The history count check is what proves the reset does not clear the list.
Alternatives and why they are weaker:
- Putting the three assignments directly in the button's closure would work, but the rule would live in the view. You could not test it, and a second button would have to copy it.
- Resetting the choices by creating a new
RollViewModel()would also clear the history, because the new instance starts empty. That is the wrong behavior for this challenge. - Writing the method with
quantity = 1butmodifier = 0in the test only, without the reset, would prove nothing. The test must start from non-default values.
Extra Practice Answers
Exercise 13.1 — A struct inside a class
The output is 4 2.
copy is a Settings value. Assigning box.settings to copy makes an independent copy of the struct at that moment. Changing copy.quantity to 4 changes only the copy. Changing box.settings.quantity to 2 changes the Settings value stored inside the Box object, which is a different value. The fact that Box is a class does not make Settings shared, because Settings is a struct. Only the Box object itself is shared between variables that refer to it.
Exercise 13.2 — Clearing from the view
The build fails. The compiler reports an error about the history property. The message will be similar to a message saying that the setter is inaccessible, because history is declared private(set) and removeAll() changes the array. The error relates to encapsulation: the view model protects its results so that every change goes through its own methods.
The fix is to call the view model's method instead: viewModel.clearHistory(). That method both empties the array and saves the empty file. The button's .disabled modifier does not need to change.
Exercise 13.3 — Making the quantity read-only
After the change, the line in ContentView that creates the RollOptionsView stops compiling:
RollOptionsView(quantity: $viewModel.quantity, modifier: $viewModel.modifier)
The compiler reports that quantity cannot be written through the binding. A message similar to the setter-inaccessible error appears. The Stepper inside RollOptionsView must write the value it changes, so the binding needs write access to the property.
This shows why the design protects the results but not the choices. An input that a control writes has to be writable from outside the class. To protect quantity while keeping the binding, you would need a method for each input, such as setQuantity(_:), and a binding that calls that method. That is more code, and for this app the range rules in DiceRoller already keep the values safe. Revert the change before you continue.
Exercise 13.4 — A corrupt history file
Tracing loadHistory():
store.load()checks whether the file exists. It does, so it reads the data.JSONDecoder().decode([RollResult].self, from: data)fails becausenot jsonis not valid JSON. Theload()function throws.- Execution jumps to the
catchblock inloadHistory(). ThehistoryandlatestRollassignments were never reached. - The
printin thecatchblock writes a line to the debug console beginning "Could not load roll history:".
After the function returns, history.count is 0 and latestRoll is nil. The user sees the empty-history message, "No rolls yet," and no alert. The console is the only place the error appears.
One consequence is easy to miss. The corrupt file is still on disk after launch. The next roll calls saveHistory(), which writes the new one-item history with an atomic write, and that replaces the corrupt file. The old contents are lost. A production app would keep a copy or ask the user, but this app accepts that trade-off.