Chapter 13 Exercises — Architecture and the View Model
These exercises extend Chapter 13. Do the Independent Challenge on a separate Git branch so your guided project stays identical to the reference checkpoint:
First commit and tag the guided work using the workbook's Development Checkpoint. Confirm git status --short prints nothing, then create the branch:
git switch -c challenge-13
Commit your challenge work on that branch as you like. Before you start Chapter 14, return to the guided project:
Uncommitted edits can follow you across branches. Save them before switching; if nothing changed, skip add and commit. The status command should print nothing:
git add -A
git commit -m "Challenge 13: Save practice work"
git status --short
git switch main
Hints get progressively more specific. Try each challenge for a while before you open Hint 1, and try again after each hint. Full solutions are in the Chapter 13 Answer Key.
Challenge 1 — Reset the choices, not the history
Goal: give the user a one-tap way to return the die, quantity and modifier to their starting values, while keeping the roll history exactly as it is.
Requirements:
- Add a method
resetChoices()toRollViewModel. It setsselectedDieto.d6,quantityto1andmodifierto0. It must not changehistory,latestRollorrollCount. - In
ContentView, add a button labeled Reset choices to the settings card, below the haptic toggle. Its action callsviewModel.resetChoices(). To place the button below the toggle, wrap the toggle and the button in aVStackwithalignment: .leadingandspacing: 12. - Add a test named
resetChoicesKeepsHistorytoRollViewModelTests. The test rolls once, changes the three choices, callsresetChoices(), and then checks that the choices have their starting values and that the history still has one item.
Acceptance criteria:
- The rule for resetting is inside
RollViewModel.ContentViewonly calls the method. - Tapping Reset choices returns the die picker to D6 and the steppers to 1 and +0. The history rows do not change.
- The new test passes with ⌘U, and the existing tests still pass.
- The project builds with no errors and no warnings.
Hint 1
Think about where each piece of the rule belongs. The choices are properties of RollViewModel, so the method that resets them belongs in that class, next to clearHistory(). The button only needs to call that method. Ask yourself which of the three properties the method must change, and which it must leave alone.
Hint 2
Your method body is three assignments. Remember that the choices are plain var properties, not private(set), so the method inside the class can set them, and the view can also set them through bindings. Check your method against the words "it must not change history": a method that calls saveHistory() or touches the list is doing too much.
For the button, look at the existing Button("Clear") { ... } in historySection. Your button follows the same pattern. The only thing you must add is the VStack that holds the toggle and the button. Wrap the existing Toggle exactly as it is, and put the button after it inside the same stack.
Hint 3
The method has three lines, one for each choice, using the starting values. The button is the same pattern as Clear, but the label and the method name change. In the test, use the same helper as the other tests, then call the method you wrote, then check three properties and one count. Compare your test with rollUsesCurrentSelections, which uses the same makeViewModel() helper and the same #expect style. If the test fails, read the failing line in the Test navigator to see which expected value was wrong.
Extra Practice
These exercises do not have hints or a full answer in this document. Work each one on paper or in a #Playground before you check the answer key. Exercises 13.2 and 13.3 change project code, so use the challenge-13 branch for them and return to main afterward.
Exercise 13.1 — Predict: a struct inside a class
Predict the output of this code. It is not part of the project, so you can run it in a #Playground:
struct Settings {
var quantity = 1
}
final class Box {
var settings = Settings()
}
let box = Box()
var copy = box.settings
copy.quantity = 4
box.settings.quantity = 2
print(copy.quantity, box.settings.quantity)
Write down the two numbers before you run it. Then explain why the copy variable is not affected by the change to box.settings.quantity, even though the Settings value lives inside a class.
Exercise 13.2 — Spot the bug: clearing from the view
A teammate adds the following to the Clear button in historySection. Predict what happens when the project is built, and say which chapter concept the error relates to. Do not change the project to make it compile. Explain what you would change instead.
Button("Clear") {
viewModel.history.removeAll()
}
.disabled(viewModel.history.isEmpty)
Exercise 13.3 — Modify and predict: making a choice read-only
On the challenge-13 branch, change the declaration of quantity in RollViewModel from var quantity: Int = 1 to private(set) var quantity: Int = 1. Before you build, predict which line in ContentView will stop compiling and what the problem is. Then build and check your prediction. Explain why the stepper in RollOptionsView needs write access, and why that means the quantity cannot be protected the way history is. Revert the change when you are done.
Exercise 13.4 — Trace: a corrupt history file
Suppose the file roll-history.json contains the text not json when the app launches. Trace what happens in loadHistory(), one line at a time. Write down the value of history.count and latestRoll after the function returns. Then say where the error message is printed and whether the user sees it on screen. Then check your reasoning against the test corruptFileThrowsAnError in HistoryStoreTests.swift, which writes the same text to a file and expects load() to throw.