Dice Foundry Exercises and Challenges

Chapter 9 Exercises — Persistent Storage

These exercises build on the Chapter 9 project. Do them 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-09

When you are finished, commit your work on the branch, even if it is unfinished (or run git stash -u to set it aside), and only then return to the main line. Uncommitted edits and new untracked files follow you across git switch, and because Xcode folders mirror the disk, a leftover file such as a new view would be compiled into your main project. Then switch back:

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 09: Save practice work"
git status --short
git switch main

Solutions are in the Chapter 9 Answers document. Try each hint in order and only read the next one when you are stuck.

Challenge 1 — A human-readable history file

Goal: make roll-history.json easy to read when you inspect it with cat.

Requirements:

  • Change only HistoryStore.swift.
  • The saved JSON is indented across multiple lines.
  • The keys inside each roll appear in alphabetical order (date, dieType, id, modifier, values) every time.

Acceptance criteria:

  • The project builds with no errors or warnings.
  • A history file saved before your change still loads after it.
  • After a roll, cat "$(xcrun simctl get_app_container booted <your bundle id> data)/Documents/roll-history.json" shows indented, multi-line JSON with alphabetical keys.
  • Stop and Run still restores the history.

Hint 1

The format of the output is controlled by the encoder, not by RollResult. Right now save(_:) creates a JSONEncoder and uses it in a single expression, so there is no chance to configure it. Can you create the encoder on its own line first?

Hint 2

JSONEncoder has a property named outputFormatting. It accepts a set of options written like an array literal. Look for options whose names describe "pretty printed" and "sorted keys".

Hint 3

Inside save(_:): create let encoder = JSONEncoder(), assign encoder.outputFormatting = [ ... ] with two options, then use encoder.encode(history) (still with try) instead of JSONEncoder().encode(history). The decoder does not care about whitespace or key order, so load() needs no change.

Challenge 2 — Tell the user when history could not be loaded

Goal: if the saved history file is corrupt, show a message in the History section instead of only printing to the console.

Requirements:

  • Add one new @State property to ContentView to hold the message (or the absence of one).
  • Set it in the catch block of loadHistory().
  • Remove the message once the history has been saved successfully. (After the next roll, the bad file has been replaced, so the message is no longer true.)
  • Show the message in red text in the History section, below the header.

Acceptance criteria:

  • With no file (first launch) or a valid file, no message appears.
  • After replacing the file with junk and relaunching, the message appears and the console still shows the decoding error.
  • After the next roll, the message disappears. Stop and Run: it does not come back.

To create a corrupt file, run the app once, then in Terminal (with your bundle identifier):

echo "not json" > "$(xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data)/Documents/roll-history.json"

Then Stop and Run from Xcode.

Hint 1

"A message, or no message" is exactly what an optional is for. You used RollResult? for latestRoll in Chapter 8. What type would hold "maybe a piece of text"? Give it no initial value so it starts as nil.

Hint 2

To display the message only when it exists, unwrap the optional in body the same way the result area unwraps latestRoll. Put that if let block inside the History VStack, between the header HStack and the "No rolls yet" check. Why can't you rely on the Clear button to remove the message? (Look at its .disabled modifier and think about what history contains after a failed load.)

Hint 3

In loadHistory()'s catch, assign a string such as "Saved history could not be loaded." to your new property. In saveHistory(), add a line directly after try store.save(history) that sets the property back to nil. Because that line comes after the try, it only runs when the save succeeded.

Extra Practice

Exercise 9.1 — Predict the file

A user on a fresh install rolls 2D8 with modifier -1 and gets 3 and 8. Without running anything, write down the JSON array that JSONEncoder produces (you may invent the UUID and date number). Which fields are present? Is total in the file? What is the value of dieType? What kind of value is date?

Exercise 9.2 — Spot the bug

A colleague's version of clearHistory() looks like this. The Clear button works on screen. What goes wrong, and when would a user notice?

Broken code — for diagnosis practice
    func clearHistory() {
        history.removeAll()
        latestRoll = nil
    }

Exercise 9.3 — Spot the bug

This version of loadHistory() does not compile. Read it and explain what the compiler will complain about and how to fix it, without changing HistoryStore.

Broken code — for diagnosis practice
    func loadHistory() {
        history = try store.load()
        latestRoll = history.first
    }

Exercise 9.4 — Think it through

Suppose a user already has 50 rolls saved, and you release an update that changes maximumCount to 20. With the current performRoll() code, what does the user see right after launching the update? What happens to the count after each new roll? Is this a problem? Describe (in words, not code) one way to make the history drop to 20 immediately.

Exercise 9.5 — Choose the mechanism

For each piece of data, choose UserDefaults, a file, or SwiftData, and give a one-sentence reason: (a) whether the user prefers dark dice; (b) a campaign tracker with players, sessions, and thousands of rolls you want to filter by player; (c) an exported PDF of a character sheet; (d) the last die type the user selected.