Chapter 9 Answers — Persistent Storage
Knowledge Check Answers
1. Volatile versus persistent data.
Volatile data lives in memory and disappears when the process ends; persistent data is written to storage and survives termination, relaunch and restarts. In Dice Foundry, selectedDie, quantity and modifier are volatile: after a relaunch they reset to D6, 1 and 0. The roll history is persistent: it is held in @State while the app runs and also written to roll-history.json in the Documents directory, then loaded again at launch. (latestRoll is volatile itself, but it is restored indirectly from history.first.)
2. Missing file versus corrupt file.
A missing file is the normal state on first launch (and after the app is deleted and reinstalled), so it means "no history yet" and the correct result is []. Treating it as an error would print a misleading failure on every fresh install. A file that exists but cannot be read or decoded means something unexpected happened: corruption, a hand edit, or a model change. Hiding that would make bugs invisible, so load() throws and the caller (loadHistory()) prints the error. The principle: expected empty states are values; genuine failures are errors.
3. .atomic.
It protects against a partially written file, for example if the app is terminated or the device loses power in the middle of a write. Foundation writes the data to a temporary file and then replaces the destination in a single step, so the destination always contains either the complete old file or the complete new one. It is the same pattern as writing config.tmp and renaming it over config.
4. JSON file versus UserDefaults versus SwiftData.
UserDefaults is designed for small preferences that are loaded into memory at launch, not for a list of records. A file is a natural fit for a small, bounded list that is always loaded and saved as a whole, needs no queries or relationships, and is easy to inspect. SwiftData would be better if the data grew large or unbounded, needed searching, filtering or sorting without loading everything, had relationships between kinds of records (players, campaigns, sessions), needed in-place edits of individual records, or needed iCloud sync.
5. static and removeLast().
The limit is a rule of the storage design that applies to every store and is needed without creating an instance (ContentView reads HistoryStore.maximumCount), so it belongs to the type: static. New rolls are inserted at index 0, so the array is ordered newest first and the last element is always the oldest roll. Removing the last element keeps the newest 50.
Challenge Solutions
Challenge 1 — A human-readable history file
File: HistoryStore.swift · Where: inside save(_:) · Action: Replace the first line of the function body.
Before:
func save(_ history: [RollResult]) throws {
let data = try JSONEncoder().encode(history)
try data.write(to: fileURL, options: .atomic)
}
After:
func save(_ history: [RollResult]) throws {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(history)
try data.write(to: fileURL, options: .atomic)
}
Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Solution folder: challenge-solutions/ch09-pretty-json/.
Why it works. JSONEncoder is a class with configuration properties. Creating it on its own line gives you a name (encoder) to configure before encoding. outputFormatting is an option set: .prettyPrinted adds line breaks and indentation, and .sortedKeys writes object keys in alphabetical order, so the output is stable from save to save. encoder is a let even though you change one of its properties; that is allowed because JSONEncoder is a class (a reference type), which Chapter 13 explains. load() needs no change because JSON readers ignore whitespace and key order, so old compact files and new pretty files both decode.
Alternatives and trade-offs. You could use only .sortedKeys (stable but still one line) or only .prettyPrinted. Pretty printing makes the file somewhat larger, which is irrelevant at 50 rolls. Stable key order is also valuable if you ever keep such files in Git, because diffs become meaningful. For readable dates you could set encoder.dateEncodingStrategy = .iso8601, but then the decoder must use the same strategy, and existing files with numeric dates would no longer decode, so that change needs care.
Challenge 2 — Tell the user when history could not be loaded
File: ContentView.swift. Four small changes.
- Where: with the other
@Stateproperties, afterhistory· Action: Add
@State private var loadErrorMessage: String?
- Where: inside
body, in the HistoryVStack, after the headerHStackand beforeif history.isEmpty· Action: Add
if let message = loadErrorMessage {
Text(message)
.foregroundStyle(.red)
}
- Where: in
loadHistory(), insidecatch, after theprint· Action: Add
loadErrorMessage = "Saved history could not be loaded."
- Where: in
saveHistory(), insidedo, directly aftertry store.save(history)· Action: Add
loadErrorMessage = nil
Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Solution folder: challenge-solutions/ch09-load-error-notice/.
Why it works. The optional String? models "a message or none" and starts as nil, so nothing appears normally. If store.load() throws, control jumps to catch, which sets the message; that is a @State change, so SwiftUI re-renders and the if let block shows the red text. On the next roll, saveHistory() runs; if try store.save(history) succeeds, the following line clears the message. If the save throws, that line is skipped, so the message is cleared only when the bad file really has been replaced.
Why not clear it in clearHistory()? After a failed load, history is empty, so the Clear button is disabled (.disabled(history.isEmpty)) and the user cannot tap it. Tying the message to a successful save matches what actually fixes the problem.
Alternatives. You could store a Bool (loadFailed) and put the text in body; that works but separates the condition from its wording. A SwiftUI alert is another option, but alerts are not taught in this course and interrupt the user for a non-critical problem. A more protective app would also rename the corrupt file aside (for example to roll-history.corrupt.json) before overwriting it, so the data could be recovered.
Extra Practice Answers
9.1 — Predict the file. Something like:
[{"values":[3,8],"id":"5A1F...-...","modifier":-1,"dieType":8,"date":818130000.25}]
Present: id, dieType, values, modifier, date (in any order). total is not in the file, nor are subtotal, notation or valuesDescription, because computed properties are not encoded. dieType is 8, the raw value of .d8. date is a number: seconds (with a fractional part) since January 1, 2001, 00:00:00 UTC, which is JSONEncoder's default date encoding.
9.2 — Spot the bug. The function clears memory but never calls saveHistory(), so the file on disk still holds the old rolls. Everything looks correct until the app is relaunched; then loadHistory() reads the old file and the "cleared" rolls reappear. (A roll after Clear would save the new, short list and hide the bug, which is why it can be hard to notice.) Fix: call saveHistory() after history.removeAll(). Setting latestRoll = nil is a design choice, not a bug.
9.3 — Spot the bug. store.load() throws, and loadHistory() is not a throwing function, so the error has nowhere to go. The compiler reports a message similar to "Errors thrown from here are not handled". Fix: wrap the two lines in do { ... } catch { print(...) }, as in the reference. (Marking loadHistory() as throws would only move the problem to .onAppear, whose closure cannot throw.)
9.4 — Think it through. Right after launching, the user still sees all 50 rolls, because loading does not trim. Each new roll inserts one item and removes one (51 > 20), so the count stays at 50, not 20. The if only ever removes one item because it assumes the list is at most one over the limit. That is a real (if minor) bug introduced by changing the limit. One fix: after loading, keep only the first maximumCount items; another: in performRoll(), keep removing the last item while the count is over the limit. Chapter 6 taught you the for loop; a while loop or taking a prefix of the array would also do it.
9.5 — Choose the mechanism. (a) UserDefaults: a single small preference. (b) SwiftData: many records, relationships, and filtering. (c) A file: it is a self-contained document, and a PDF is a file format. (d) UserDefaults: a tiny setting (for example the raw value 20 under a key); this is exactly what Chapter 11's @AppStorage is good for.