Chapter 9 — Persistent Storage
At the end of Chapter 8, Dice Foundry keeps a tidy history of every roll. Stop the app and run it again, and that history is gone. Everything the app knows lives in memory, and memory is released when the process ends. In this chapter you give the app a memory that outlives the process: every time the history changes, the app writes it to a small JSON file inside its own private storage area, and every time the app starts, it reads that file back. Along the way you meet three ideas that appear in almost every real app: serialization (turning values into bytes and back), Swift's error handling (throws, try, do, catch), and the question of where data should live (preferences, files, or a database). By the end, your roll history survives quitting the app, relaunching it from Xcode, and relaunching it from the Home Screen, and it never grows beyond 50 entries.
Learning Objectives
By the end of this chapter you will be able to:
- Explain the difference between volatile data (memory) and persistent data (storage), and say which parts of Dice Foundry are which.
- Describe the iOS application sandbox and the role of the app's Documents directory.
- Explain serialization and read a JSON document produced by your own app.
- Make your own types
Codableand explain what the compiler generates for you. - Encode an array of structs to JSON with
JSONEncoderand decode it back withJSONDecoder. - Write functions that
throw, call them withtry, and handle failures withdoandcatch. - Explain why an atomic write protects a file from being half-written.
- Choose between
UserDefaults, a file, and a database (such as SwiftData) for a given kind of data, and justify the choice for Dice Foundry. - Keep stored history bounded with a
staticlimit so the file cannot grow forever. - Load saved data when a view appears using
.onAppear. - Test persistence deliberately: stop and relaunch from Xcode, terminate from the app switcher, inspect the file with
xcrun simctl, and verify the history limit. - Recognize
guardwhen you meet it in other code.
Concept Explanation
Volatile versus persistent data
Every @State property you have written so far lives in the app's memory (RAM). Memory is fast, but it is volatile: when the process ends, the operating system reclaims it and every value in it disappears. A process can end for many reasons:
- You press Stop (⌘.) in Xcode.
- The user swipes the app away in the app switcher.
- iOS terminates a suspended app in the background to free memory for something else. This happens silently and often.
- The device restarts.
- The app crashes.
Persistent data is written to storage (the device's flash storage) and survives all of these. To make data persistent you must do two things yourself: write it to storage at the right moments, and read it back when the app starts. Nothing in SwiftUI does this automatically for an ordinary @State array.
You already know this distinction from servers. A process's heap is gone after a restart; only what was flushed to disk survives. An app is the same. @State private var history is the in-memory working set. The JSON file you create in this chapter is the on-disk copy. The interesting engineering questions are the same ones you ask about any service: when do we flush, what happens if we crash mid-write, and what do we do if the file on disk is unreadable at startup?
In Dice Foundry after this chapter:
| Data | Where it lives | Survives relaunch? |
|---|---|---|
selectedDie, quantity, modifier |
@State in memory |
No (they reset to D6, 1, 0) |
latestRoll |
@State in memory, restored from history at launch |
Yes, indirectly |
history |
@State in memory and roll-history.json on disk |
Yes |
Notice that we deliberately do not persist the dice controls. A fresh launch starting at "1 D6, modifier 0" is reasonable behavior. Deciding what not to save is as much a design decision as deciding what to save.
The application sandbox
On a Mac or a Linux server, a process can usually read any file its user account can read. iOS is much stricter. Every app is installed into its own sandbox: a private set of directories that only that app can read and write. An app cannot see another app's files, and other apps cannot see its files. The system enforces this; it is not a convention.
Inside an app's sandbox (its data container) there are a few standard directories:
| Directory | Purpose | Backed up? |
|---|---|---|
Documents/ |
Data the user creates or would be upset to lose | Yes (iCloud/computer backups) |
Library/Application Support/ |
App-managed data files the user never sees directly | Yes |
Library/Caches/ |
Data that can be re-created; the system may delete it when space is low | No |
tmp/ |
Short-lived scratch files; the system may delete them at any time | No |
Roll history is user-created data that should be backed up with the device, so we store it in Documents. (Library/Application Support would also be a perfectly good choice; many apps use it for files the user never browses. Documents is easier to find when you inspect the simulator later in this chapter, which is a useful property in a course.)
If you have run a process in a chroot jail or given a container a dedicated volume, you already understand the sandbox. The app sees its own little file system tree, and paths outside it are simply not available. Deleting the app is like deleting the container and its volume: the data goes with it.
Two practical consequences follow:
- You never hard-code a path such as
/Users/you/...or/var/mobile/.... The location of the sandbox differs between devices, simulators and even installs. You ask the system for the Documents directory, and it gives you a URL. - Deleting the app deletes its sandbox. If you delete Dice Foundry from the simulator's Home Screen, its history file is deleted too. That is expected and is a good way to get back to a clean first-launch state.
Preferences, files, and databases
Apple platforms give you several places to put persistent data. Choosing well is one of the most useful skills you can take to your other apps.
Preferences: UserDefaults. A small key-value store for settings: "is sound on?", "which theme?", "has the user seen the welcome screen?". Values are simple types (Bool, Int, Double, String, Date, Data, and arrays or dictionaries of those). The whole store is loaded into memory when the app starts, so it is meant to stay small. It is not meant for documents, logs, or growing lists of records.
Treat UserDefaults the way you treat /etc/someapp.conf or a handful of registry keys: a few named settings, read at startup, changed occasionally. You would not log every web request into a config file, and you should not store a growing roll history in UserDefaults.
This is what using UserDefaults directly looks like. You do not add this to the project; Chapter 11 stores a haptics preference with SwiftUI's @AppStorage, which is a convenient wrapper around exactly this mechanism.
// Write a preference
UserDefaults.standard.set(true, forKey: "hapticsEnabled")
// Read it back (returns false if the key has never been set)
let enabled = UserDefaults.standard.bool(forKey: "hapticsEnabled")
UserDefaults.standard is the app's shared preferences store. set(_:forKey:) stores a value under a string key. bool(forKey:) reads it back, returning false when the key does not exist. That last detail is why Chapter 11 will give the haptics setting an explicit default of true.
Files. You choose the format (JSON, plain text, images, PDFs) and you decide when to read and write. Files are ideal when the data is a self-contained document or a modest list that you load and save as a whole. They are simple, transparent (you can open the file and read it) and need no framework beyond Foundation.
Databases: SwiftData, Core Data, SQLite. A database stores many records and lets you query, sort, filter and update individual records without loading everything into memory. Apple's modern option is SwiftData (iOS 17 and later), which stores model objects in a database for you, with relationships between models, change tracking, undo support and optional iCloud sync. Core Data is the older framework SwiftData is built on; SQLite is the database engine underneath both.
| Mechanism | Best for | Size | Querying | Effort |
|---|---|---|---|---|
UserDefaults |
Settings and small flags | Tiny (a few KB) | Read by key | Lowest |
| File (JSON) | A document or a bounded list loaded as a whole | Small to medium | Load everything, filter in memory | Low |
| SwiftData / Core Data | Many records, relationships, searching, sync | Large | Fetch with predicates and sorting | Higher |
Why a JSON file is right for Dice Foundry
Our history is:
- Small and bounded. We keep at most 50 rolls. Each roll is roughly 120 bytes of JSON, so the whole file stays well under 10 KB.
- Always used as a whole. The app shows the entire list. It never needs "find all D20 rolls from last Tuesday" against thousands of records.
- One kind of record with no relationships. A roll does not point at a player, a campaign, or a session.
- Easy to inspect. You can open the file and read it, which makes debugging and learning easier.
Loading 50 small records and saving them again after each roll costs almost nothing. A file is the simplest mechanism that does the job, and simple is a feature: there is no schema migration, no database context, and nothing to configure.
When would SwiftData be the better choice? Consider it when you find yourself wanting any of these:
- Thousands of records, or a list that grows without a natural limit.
- Searching, filtering or sorting large data sets without loading all of it.
- Relationships between kinds of records (players, campaigns, sessions, rolls).
- Editing individual records in place rather than rewriting the whole list.
- Built-in iCloud sync across the user's devices.
If you later turn Dice Foundry into a campaign tracker with players and sessions, SwiftData would become the right tool. For a 50-item roll log, it would be machinery without a purpose.
Ask an AI assistant to "save the roll history" and you may get a SwiftData model container, a Core Data stack, or a history encoded into UserDefaults. All three can work. Ask yourself the questions from this section: how big can the data get, is it used as a whole, does it need queries or relationships? If the answer is "small, bounded, used as a whole", a JSON file is easier to read, test and debug. Conversely, if an assistant stores thousands of records in UserDefaults, push back: that store is loaded into memory at launch and is not designed for it. A good prompt names the mechanism: "Persist the history as a JSON array in a file in the Documents directory, capped at 50 entries."
Serialization and JSON
Your history is an array of RollResult structs in memory. Memory layout is not something you can write to a file and expect to read back later, possibly in a newer version of the app. You need an agreed, stable format. Converting in-memory values to a stream of bytes in such a format is called serialization (or encoding). Converting bytes back into values is deserialization (or decoding).
JSON (JavaScript Object Notation) is a text format almost every language and tool can read. It has a small set of building blocks:
| JSON | Example | Swift equivalent |
|---|---|---|
| Object (named fields) | {"modifier": 2} |
A struct's properties |
| Array | [4, 2, 6] |
[Int] |
| Number | 6, 818127280.34 |
Int, Double |
| String | "2126547B-..." |
String (and here, UUID) |
| Boolean | true |
Bool |
| Null | null |
nil |
Serializing config to disk, exporting a VM definition, kubectl get -o json, terraform show -json: all of these take a structured in-memory object and write it in a text format another process can read. JSONEncoder is the same operation for your Swift types.
Here is what Dice Foundry's history file actually contains after one roll of 3D6 + 2 that came up 4, 2, 6. JSONEncoder writes compact JSON with no spaces or line breaks, so if you print the file with cat it is a single long line:
[{"values":[4,2,6],"id":"2126547B-E4BB-4A5F-91FF-C9C1BEF096AE","modifier":2,"dieType":6,"date":818127280.341869}]
The same content, reformatted for readability (the app does not write it this way):
[
{
"values" : [ 4, 2, 6 ],
"id" : "2126547B-E4BB-4A5F-91FF-C9C1BEF096AE",
"modifier" : 2,
"dieType" : 6,
"date" : 818127280.341869
}
]
Read it field by field:
- The outer
[ ... ]is a JSON array: the[RollResult]array. Each{ ... }is oneRollResult. "values"is the[Int]array of individual dice."id"is theUUID, written as an uppercase string."modifier"is theInt."dieType" : 6is the enumDieType.d6. BecauseDieTypehasIntraw values, Swift encodes each case as its raw value. A D20 roll would show20."date"is theDate. By default,JSONEncoderwrites aDateas a number: the seconds since January 1, 2001, 00:00:00 UTC (Apple's "reference date"), with a fractional part. It is not a Unix timestamp (which counts from 1970), and it is not a human-readable date string.818127280seconds after the start of 2001 is a moment in December 2026.- The order of the keys is not guaranteed. Your file may list
idfirst, ordatefirst. JSON readers do not care about key order, and neither doesJSONDecoder. - Computed properties (
subtotal,total,notation,valuesDescription) are not in the file. Only stored properties are encoded. That is good design: the file holds the facts, and everything derived from them is recalculated when needed, so it can never disagree with them.
Codable: teaching the compiler your format
How does JSONEncoder know how to turn a RollResult into those fields? You tell Swift that the type is Codable.
Codable is not one protocol but two combined:
Encodable: "this type can write itself out."Decodable: "this type can be created from encoded data."
Codable means both. When you add Codable to a struct whose stored properties are all Codable themselves, the compiler generates the encoding and decoding code for you. UUID, Int, [Int] and Date are already Codable in the standard library and Foundation. DieType is ours, so we must make it Codable too; an enum with raw values gets the conformance generated as well, encoding the raw value.
Marking a type Codable is a bit like annotating a struct with JSON tags in Go, or writing a schema for a config format, except the compiler writes the reader and writer for you. If a field's type cannot be serialized, the build fails, rather than failing at 2 a.m. in production.
If a property's type is not Codable, the compiler refuses to generate the conformance and the build fails with a message similar to "Type 'RollResult' does not conform to protocol 'Decodable'". You will see this in Troubleshooting.
Encoding and decoding
Two Foundation classes do the actual work:
JSONEncoder().encode(value)takes anyEncodablevalue and returnsData: a buffer of raw bytes (here, the UTF-8 text of the JSON).JSONDecoder().decode(Type.self, from: data)takesDataand the type you expect, and returns a value of that type.
Data is Foundation's type for "a bag of bytes". Data(contentsOf: url) reads a file into a Data value, and data.write(to: url) writes one out.
If the diagram is not available in your copy, here is the same flow in text:
SAVE LOAD
history: [RollResult] history: [RollResult]
| ^
v JSONEncoder().encode(history) | JSONDecoder().decode(...)
Data (UTF-8 JSON bytes) Data (UTF-8 JSON bytes)
| ^
v data.write(to: fileURL, options: .atomic) | Data(contentsOf: fileURL)
+---------------------------------------------------------------------+
| App sandbox > Documents/ > roll-history.json |
+---------------------------------------------------------------------+
Errors, and why file work can fail
Everything you have written so far either works or is a bug in your code. File and format work is different: it can fail for reasons outside your code's control.
- The file might not exist yet (first launch).
- The storage might be full when you write.
- The file might be corrupt (truncated, edited by hand, written by an incompatible version of the app).
- The JSON might be valid but not match your types (a missing field, a string where a number should be).
Swift makes this explicit with error handling. A function that can fail in a way the caller should deal with is marked throws. When it fails, it throws an error instead of returning a value. Every call to a throwing function must be marked with try, so you can see at a glance which lines can fail. Somewhere up the chain, a do / catch block catches the error and decides what to do.
func riskyOperation() throws -> Int {
// ... may throw an error instead of returning ...
return 42
}
do {
let value = try riskyOperation() // if this throws, jump to catch
print("Got \(value)") // only runs on success
} catch {
print("Failed: \(error)") // `error` holds what was thrown
}
Three rules cover almost everything you will read:
throwsin a function's declaration means "this can fail; callers must usetry."tryin front of a call marks a point where control may leave immediately. If the call throws, the rest of thedoblock is skipped.- Inside
catch { }, Swift gives you a constant namederrordescribing what went wrong. You can print it, show a message, or recover.
A throwing function does not have to catch its own errors. It can let them propagate to its caller by using try without a do / catch. That is exactly what HistoryStore does: it reports failures, and the view decides how to handle them. You will also see two shorter forms in other people's code:
try?converts a failure intoniland discards the error ("I don't care why it failed").try!crashes the app if the call throws ("this cannot fail"). Treattry!with suspicion in file or network code.
We use neither in this chapter. We want to see the error in the console when something goes wrong.
In a shell script you check $? after each command, or use set -e to abort on the first failure. Swift's try is like a per-call set -e: a failure aborts the current block and jumps to the nearest catch, which is your || handle_error. The compiler forces you to mark every call that can fail, so you cannot forget to check one.
A missing file is normal; a corrupt file is an error
The first time anyone launches Dice Foundry, roll-history.json does not exist. That is not an error; it means "no history yet". So our load() checks whether the file exists, and if not, returns an empty array.
If the file does exist but cannot be read or decoded, something unexpected happened. Hiding that would make bugs invisible, so load() lets the error propagate (throws), and the view prints it. This distinction between "expected empty state" and "genuine failure" is one you will make in every app that stores data.
There is an honest consequence to understand. If loading fails, history stays empty, and the next roll saves that new, shorter history over the corrupt file. The corrupt data is then gone. For a roll log, that trade-off is acceptable: the app keeps working and the user loses only an unreadable file. For important user documents you would do more, such as renaming the bad file aside before overwriting it, or telling the user. One of this chapter's challenges explores showing a message.
Atomic writes
What happens if the app is terminated halfway through writing the file? With a plain write, you could be left with half a JSON document, which would fail to decode on the next launch.
Passing options: .atomic to write(to:options:) asks Foundation to write the data to a temporary file first and then replace the real file with it in one step. Either the old complete file or the new complete file exists; never a half-written one.
This is the same pattern you use for config deployment: write app.conf.tmp, fsync, then mv app.conf.tmp app.conf. A rename within one file system is atomic, so readers see either the old file or the new one. .atomic does that dance for you.
static: values that belong to the type
So far every property you have written belongs to an instance: each RollResult has its own values, each ContentView has its own history. Sometimes a value belongs to the type itself, shared by every instance and needed without creating one. That is what static means.
struct HistoryStore {
static let maximumCount = 50 // one value for the whole type
let fileURL: URL // one value per instance
}
HistoryStore.maximumCount // 50, read through the type name
The history limit is a rule of the storage design, not a property of any particular store, so it is static. You read it as HistoryStore.maximumCount (type name, dot, property), without having a HistoryStore value in hand. Chapter 10 uses the same keyword for a function, and Chapter 11 uses static let for theme constants.
Bounded history
A list that only ever grows is a slow leak: the file gets bigger, saving takes longer, and the screen fills with rolls nobody will scroll back to. We cap the history at 50. Because new rolls are inserted at index 0, the oldest roll is always the last element. After inserting, if the array has more than 50 elements, we remove the last one.
This is logrotate with rotate 50, or a ring buffer: keep the newest N entries and drop the oldest. Bounded growth is a property you want in every store you design.
When to load: .onAppear
We need to read the file when the app starts. The natural place is when ContentView appears on screen. SwiftUI's .onAppear { } modifier runs its closure when the view it is attached to appears. We attach it to the outermost view in body (the ScrollView), so it runs once when the screen is first shown.
.onAppear is a view modifier like .padding(), but instead of changing appearance, it attaches an action to a moment in the view's life. Its closure is just like a button's action closure (Chapter 4), except SwiftUI calls it instead of a tap.
Recognizing guard
You will often see AI-generated and professional Swift code use guard for early exits:
func load() throws -> [RollResult] {
guard FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) else {
return []
}
let data = try Data(contentsOf: fileURL)
return try JSONDecoder().decode([RollResult].self, from: data)
}
Read guard condition else { exit } as "make sure this is true; if it is not, leave now". The else block must exit the current scope (with return, throw, or similar). It does the same job as our if !condition { return [] }. We use the if form in this course because you already know it; just recognize guard when you see it.
Syntax Breakdown
Adding a protocol to a type
enum DieType: Int, CaseIterable, Identifiable, Codable {
| Token | Meaning |
|---|---|
enum DieType |
Declares the enumeration you created in Chapter 5. |
: |
Introduces the raw value type and the list of protocols the type conforms to. |
Int |
The raw value type (each case has an Int raw value). |
CaseIterable, Identifiable |
Existing conformances from Chapter 5. |
, Codable |
New: the type can be encoded and decoded. For a raw-value enum the compiler generates code that writes the raw value (6) and reads it back. |
struct RollResult: Identifiable, Codable { works the same way. The compiler generates encoding for each stored property (id, dieType, values, modifier, date).
A static constant
static let maximumCount = 50
| Token | Meaning |
|---|---|
static |
Belongs to the type, not to an instance. Accessed as HistoryStore.maximumCount. |
let |
A constant; it cannot change. |
maximumCount |
The name. Reads naturally at the use site: history.count > HistoryStore.maximumCount. |
= 50 |
The value; Swift infers Int. |
An initializer with a computed default
init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
| Token | Meaning |
|---|---|
init(...) |
A custom initializer, as in Chapter 8. |
fileURL: URL |
One parameter, named fileURL, of type URL (Foundation's type for file and web addresses). |
= ... |
A default value, as with id: UUID = UUID() in Chapter 8. Callers can omit the argument. |
URL.documentsDirectory |
A static property on URL (iOS 16+) that gives the URL of this app's Documents directory inside its sandbox. |
.appending(path: "roll-history.json") |
Returns a new URL with a file name added to the end of the directory URL. |
Why accept the URL as a parameter at all, if the app always uses the default? Because it lets other code, specifically the tests in Chapter 12, create a HistoryStore that writes to a temporary file instead of your real history. Making a dependency replaceable with a default value is a pattern you will use again.
A throwing function declaration
func load() throws -> [RollResult] {
| Token | Meaning |
|---|---|
func load() |
A method with no parameters. |
throws |
This function can fail by throwing an error. Callers must use try. throws goes before the ->. |
-> [RollResult] |
On success, it returns an array of roll results. |
func save(_ history: [RollResult]) throws { has one unlabeled parameter (_, Chapter 4), throws, and returns nothing.
Checking whether a file exists
if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
| Token | Meaning |
|---|---|
FileManager.default |
Foundation's shared file manager, which performs file system operations. |
.fileExists(atPath:) |
Returns true if a file exists at the given path string. |
fileURL.path(percentEncoded: false) |
Converts the URL to a plain path string, which is what fileExists(atPath:) expects. percentEncoded: false keeps spaces and other characters as they are (/tmp/a b/x.json). Without it, path() returns the encoded form (/tmp/a%20b/x.json), and the file check fails for names with spaces. |
! |
Logical NOT (Chapter 7): "if the file does not exist". |
Reading, decoding, encoding and writing
let data = try Data(contentsOf: fileURL)
| Token | Meaning |
|---|---|
try |
This call can throw (for example, if the file cannot be read). |
Data(contentsOf: fileURL) |
Creates a Data value holding every byte of the file. |
let history = try JSONDecoder().decode([RollResult].self, from: data)
| Token | Meaning |
|---|---|
JSONDecoder() |
Creates a decoder. |
.decode(_:from:) |
Decodes the bytes. Throws if the JSON is invalid or does not match the type. |
[RollResult].self |
The type itself passed as a value: "decode an array of RollResult". .self after a type name refers to the type rather than an instance. |
from: data |
The bytes to decode. |
let data = try JSONEncoder().encode(history) creates an encoder and turns the array into Data. Encoding can throw too, although for simple types like ours it essentially never does.
try data.write(to: fileURL, options: .atomic)
| Token | Meaning |
|---|---|
data.write(to:options:) |
Writes the bytes to the file at the URL, creating or replacing it. |
options: .atomic |
Write to a temporary file, then replace the destination in one step. |
do and catch
do {
history = try store.load()
latestRoll = history.first
} catch {
print("Could not load roll history: \(error)")
}
| Token | Meaning |
|---|---|
do { ... } |
A block whose try calls are protected by the following catch. |
try store.load() |
If load() throws, execution jumps straight to catch; the next line does not run. |
history.first |
The first element of the array, or nil if the array is empty. Its type is RollResult?, which matches latestRoll. |
catch { ... } |
Runs only if something in the do block threw. |
error |
An implicit constant available inside catch, holding the thrown error. |
onAppear
.onAppear { loadHistory() }
| Token | Meaning |
|---|---|
.onAppear |
A modifier that runs an action when the view appears. |
{ loadHistory() } |
A trailing closure (Chapter 3/4) containing the action. |
Guided Implementation
You will make the model types Codable, create a small storage type, connect it to ContentView, and then test persistence thoroughly. The project builds after every step.
Start from your completed Chapter 8 project. If you want to be sure your starting point matches, compare it with Reference-Checkpoints/Checkpoint-08-Roll-History.
Step 1 — Make DieType Codable
File: DieType.swift · Where: the enum DieType declaration line · Action: Replace
Before:
enum DieType: Int, CaseIterable, Identifiable {
After:
enum DieType: Int, CaseIterable, Identifiable, Codable {
What it does: declares that DieType can be encoded and decoded. The compiler generates the code, encoding each case as its raw value.
Why first: RollResult contains a dieType property. A struct can only get generated Codable support if every stored property is itself Codable, so the enum must come first.
What next: build with ⌘B. Nothing visible changes.
Step 2 — Make RollResult Codable
File: RollResult.swift · Where: the struct RollResult declaration line · Action: Replace
Before:
struct RollResult: Identifiable {
After:
struct RollResult: Identifiable, Codable {
What it does: the compiler now generates encoding and decoding for the five stored properties: id (UUID), dieType (DieType, now Codable), values ([Int]), modifier (Int) and date (Date). Computed properties are not included.
Why it is written this way: you could write the encoding code by hand, and some apps do when they need custom field names or formats. The generated version is correct, short, and updates itself when you add a stored property.
What next: build with ⌘B. If you get an error about Decodable or Encodable, check Step 1. Nothing changes on screen.
Step 3 — Create the HistoryStore file
You will put all file handling in its own small type. ContentView will ask it to load and save, without knowing anything about URLs, JSON or file managers. That keeps the view about the screen, and puts the storage details in one place you can test (Chapter 12) and change later.
File: new file HistoryStore.swift · Where: in the DiceFoundry group, next to RollResult.swift · Action: Create file
- In the Project navigator (⌘0 if it is hidden), right-click the yellow
DiceFoundryfolder that containsContentView.swift. - Choose New File from Template... (in some Xcode versions the item is called New File...).
- Select iOS at the top, then Swift File, then Next.
- Name it
HistoryStoreand make sure the DiceFoundry target checkbox is selected. Click Create.
Xcode creates a file containing a comment header and import Foundation. Replace its contents with the following. First the header, the import and the start of the struct:
//
// HistoryStore.swift
// DiceFoundry
//
import Foundation
struct HistoryStore {
static let maximumCount = 50
let fileURL: URL
init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
self.fileURL = fileURL
}
Then, still inside the struct, the load() method:
func load() throws -> [RollResult] {
if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
return []
}
let data = try Data(contentsOf: fileURL)
let history = try JSONDecoder().decode([RollResult].self, from: data)
return history
}
And finally the save(_:) method and the closing brace of the struct:
func save(_ history: [RollResult]) throws {
let data = try JSONEncoder().encode(history)
try data.write(to: fileURL, options: .atomic)
}
}
What it does:
maximumCountis the history limit, shared by the whole type.fileURLis where the history lives. By default,roll-history.jsonin the app's Documents directory.load()returns an empty array when there is no file yet (a normal first launch). Otherwise it reads the bytes and decodes them. Either of those twotrylines can throw, andload()lets the error propagate to its caller.save(_:)encodes the array and writes it atomically, replacing whatever was there.
Why it is written this way:
- It is a
structwith one stored property. It holds no history itself; it is a small tool that knows how to read and write one file. load()andsave(_:)throw instead of printing errors themselves. The store does not know whether the caller wants to log, show an alert, or retry. Reporting the error and letting the caller decide keeps it reusable.- Each step gets its own line (
let data = ...,let history = ...,return history). You could write it as one expression, but separate lines are easier to read and easier to put breakpoints on in Chapter 12.
What next: build with ⌘B. It should build cleanly. Nothing uses HistoryStore yet, so the app behaves exactly as before.
In the simulator, it is a folder deep inside ~/Library/Developer/CoreSimulator/Devices/ on your Mac. On a real iPhone, it is inside the app's container on the device. You never need to know the actual path in code; you will look it up with a Terminal command in Step 11.
Step 4 — Give ContentView a store
File: ContentView.swift · Where: inside struct ContentView, after @State private var history: [RollResult] = [] and before let columns = [ · Action: Add
let store = HistoryStore()
Leave a blank line before and after it, matching the spacing of the surrounding properties.
What it does: creates one HistoryStore using the default file URL. ContentView will call store.load() and store.save(...).
Why it is let and not @State: the store never changes and nothing on screen depends on it. It is a tool, not state. @State is only for values whose changes should update the view.
What next: build. No visible change.
Step 5 — Add saveHistory()
File: ContentView.swift · Where: inside struct ContentView, after the closing brace of performRoll() (it is the last function in the struct) · Action: Add
You will add three small functions in Steps 5 to 7. Their final order in the file is clearHistory(), loadHistory(), saveHistory(). Add saveHistory() now, directly after performRoll():
func saveHistory() {
do {
try store.save(history)
} catch {
print("Could not save roll history: \(error)")
}
}
What it does: asks the store to save the current history array. If saving fails, it prints a message with the error to Xcode's console instead of crashing.
Why it is written this way: store.save throws, so the call needs try, and something must handle a failure. ContentView is where the decision belongs. For this app, a console message is enough: a failed save is very unlikely (the file is tiny) and the in-memory history still works. In a production app you might also show the user a message.
What next: build. Nothing calls this function yet.
Step 6 — Add loadHistory()
File: ContentView.swift · Where: directly above func saveHistory() · Action: Add
func loadHistory() {
do {
history = try store.load()
latestRoll = history.first
} catch {
print("Could not load roll history: \(error)")
}
}
What it does: reads the saved history into the history state, then sets latestRoll to the newest saved roll. Because the newest roll is always at index 0, history.first is the most recent roll, or nil if there is no history.
Why set latestRoll? Without it, a relaunched app would show the full history list but the result area would say "Tap Roll Dice to begin". Restoring the last roll makes the app look exactly as the user left it. If loading fails, the catch runs, nothing is assigned, and the app starts with an empty history.
What next: build. Still nothing calls it.
Step 7 — Add clearHistory()
File: ContentView.swift · Where: directly above func loadHistory() · Action: Add
func clearHistory() {
history.removeAll()
saveHistory()
}
What it does: empties the in-memory history and then saves the empty array, so the file contains [].
Why both lines? If you only cleared memory, the next launch would load the old file and the "cleared" rolls would come back. Every change to history that should survive a relaunch needs a matching save. Chapter 12 uses exactly this mistake as a debugging exercise.
What next: build. The function exists but the Clear button still calls history.removeAll() directly. You fix that next.
Step 8 — Make the Clear button use clearHistory()
File: ContentView.swift · Where: inside body, in the history header HStack, the Button("Clear") closure · Action: Replace
Before:
Button("Clear") {
history.removeAll()
}
After:
Button("Clear") {
clearHistory()
}
.disabled(history.isEmpty)
(The .disabled(history.isEmpty) line is unchanged; it is shown so you can see where the block ends.)
What it does: tapping Clear now empties the history and saves the empty list.
Why a function and not two lines in the closure? The button's job is to say what the user wants ("clear the history"). How clearing works (memory, then disk) belongs in one named function. If clearing ever needs a third step, you change one place.
What next: build.
Step 9 — Trim and save after every roll
File: ContentView.swift · Where: inside performRoll(), directly after history.insert(roll, at: 0) · Action: Add
if history.count > HistoryStore.maximumCount {
history.removeLast()
}
saveHistory()
The whole if isValidQuantity(quantity) branch now reads:
let values = rollDice(count: quantity, sides: selectedDie.sides)
let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
latestRoll = roll
history.insert(roll, at: 0)
if history.count > HistoryStore.maximumCount {
history.removeLast()
}
saveHistory()
What it does:
- After the new roll is inserted at the front, the array may hold 51 items.
- If it holds more than
HistoryStore.maximumCount(50),removeLast()removes the final element, which is the oldest roll. saveHistory()writes the updated list to disk.
Why if and not a loop? Each roll adds exactly one item, so the array can only ever be one over the limit. A single removeLast() is enough. (If you ever lowered the limit while a larger file already existed, the list would shrink by one per roll until it reached the new limit. That is acceptable here; one of the exercises asks you to think about it.)
Why save after every roll? Rolls happen a few times a minute at most, and the file is tiny. Saving immediately means a roll is never lost, even if iOS terminates the app a second later. Saving "when the app goes to the background" is a valid alternative in bigger apps, but it adds complexity and a window in which data can be lost.
What next: build and run (⌘R). Roll a few times. Everything looks as before, but each roll is now written to disk. The history does not come back yet if you relaunch, because nothing loads it. That is the last code step.
Step 10 — Load the history when the screen appears
File: ContentView.swift · Where: inside body, after the closing brace of the ScrollView, which is directly after the .padding() line · Action: Add
.padding()
}
.onAppear {
loadHistory()
}
}
Only the three .onAppear lines are new. .padding() belongs to the VStack, the } after it closes the ScrollView, and the final } closes body. Make sure .onAppear is attached to the ScrollView (indented at the same level as ScrollView {), not inside the VStack.
What it does: when ContentView first appears, SwiftUI calls loadHistory(). That sets history and latestRoll, which are @State, so SwiftUI re-renders body and the restored history appears.
Why on the outermost view? It is the one view that represents "this screen". Attaching it deeper would work too but would make the intent less obvious.
What next: build and run. If you rolled in Step 9, those rolls should now appear immediately, because Step 9 already saved them to the file. You have working persistence. Now prove it.
Roll Dice tapped → performRoll() → rollDice(...) → RollResult(...) → latestRoll = roll → history.insert(...) → trim if over 50 → saveHistory() → store.save(history) → JSONEncoder → data.write(..., .atomic). SwiftUI then re-renders because latestRoll and history changed.
In text form:
[Roll Dice] tap
-> performRoll()
-> rollDice(count:sides:) Int.random(in: 1...sides), quantity times
-> RollResult(dieType:values:modifier:) subtotal, total, notation computed
-> latestRoll = roll @State change
-> history.insert(roll, at: 0) @State change
-> if count > 50: removeLast() oldest roll dropped
-> saveHistory() -> store.save() -> JSONEncoder -> roll-history.json (.atomic)
-> SwiftUI sees @State changed -> recomputes body -> screen updates
(In Chapter 12, rollDice is replaced by a DiceRoller, and in Chapter 13 the flow moves into a view model. The shape of the flow stays the same.)
Step 11 — Test persistence explicitly
Persistence is easy to believe in and easy to get subtly wrong. Test it on purpose, in several ways, and write down what you see.
Test A: Stop and Run from Xcode
- Run the app (⌘R).
- Tap Clear if there is any history, so you start from a known state.
- Choose D20, set the number of dice to 2 and the modifier to +3. Roll three times. Note the three totals.
- In Xcode, press Stop (⌘.). The app disappears from the simulator. The process is gone.
- Press Run (⌘R) again.
Expected: the History section shows the same three rolls, newest first, with the same totals and times. The result area shows the most recent roll (the top history entry), not "Tap Roll Dice to begin". The dice controls are back to D6, 1 die, modifier 0, because we do not persist them.
Test B: Terminate from the app switcher and relaunch from the Home Screen
This is how a real user ends the app, and it does not involve Xcode at all.
- With the app running in the simulator, open the app switcher. On a simulator for an iPhone with Face ID, use Device → App Switcher in the Simulator menu bar if available, or press ⌃⇧⌘H, or swipe up from the bottom edge and pause. (Menu names can differ slightly between Simulator versions.)
- Swipe the Dice Foundry card upward to terminate it.
- Go to the Home Screen (Device → Home, or ⇧⌘H) and tap the Dice Foundry icon.
Expected: the history is still there. Note that when you launch from the Home Screen, Xcode's debugger is no longer attached, so print output does not appear in Xcode's console. That is normal.
Relaunching from Xcode and relaunching from the Home Screen both work, because both start a new process that runs .onAppear → loadHistory() against the same file in the same sandbox.
Test C: Clear survives a relaunch
- Tap Clear. The history list shows "No rolls yet". The result area still shows the last roll, because clearing the history does not reset
latestRoll. - Stop and Run again.
Expected: "No rolls yet", and the result area says "Tap Roll Dice to begin", because the loaded history is empty and history.first is nil.
Test D: Deleting the app deletes its data
- On the simulator Home Screen, touch and hold the Dice Foundry icon, choose Remove App, then Delete App.
- Run from Xcode again. Xcode installs a fresh copy.
Expected: a first-launch state with no history. The sandbox, including roll-history.json, was deleted with the app.
Step 12 — Look at the file on disk
You can inspect the actual file the app wrote. This is the same instinct as ls and cat on a server when you want to know what really landed on disk.
- Run the app and roll a couple of times so the file exists.
- Open Terminal and run the following, replacing
com.blackwellfoundry.DiceFoundrywith your bundle identifier (Xcode: select the project, the DiceFoundry target, General → Identity → Bundle Identifier):
xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data
| Part | Meaning |
|---|---|
xcrun |
Runs a developer tool from the active Xcode. |
simctl |
The command-line tool for controlling simulators. |
get_app_container |
Prints the path of an app's container. |
booted |
Use the currently booted simulator. |
com.blackwellfoundry.DiceFoundry |
The app's bundle identifier. |
data |
Ask for the data container (the sandbox with Documents/), not the app bundle. |
It prints a long path similar to:
/Users/you/Library/Developer/CoreSimulator/Devices/<DEVICE-ID>/data/Containers/Data/Application/<APP-ID>
- Print the file, using that path (keep the quotes):
cat "$(xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data)/Documents/roll-history.json"
The $( ... ) runs the inner command and substitutes its output, so you do not have to copy the path by hand. You should see one long line of JSON like the example in the Concept Explanation, one object per roll, newest first. Roll again, run the cat command again, and you will see a new object at the start of the array.
To view it formatted, you can pipe it through Python's JSON tool, which ships with macOS developer tools:
cat "$(xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data)/Documents/roll-history.json" | python3 -m json.tool
You can also open the Documents folder in Finder:
open "$(xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data)/Documents"
If more than one simulator is booted, booted may pick a different one from the one you are looking at. Replace booted with the simulator's identifier from xcrun simctl list devices booted. The <APP-ID> part of the path changes when you delete and reinstall the app, so always run get_app_container again rather than reusing an old path. If the command says it cannot find the app, check the bundle identifier and that the app has been installed on that simulator.
Step 13 — Test the history limit
You want evidence that the history stops at 50. Two ways:
Option 1: Roll 51 or more times. Clear the history, then tap Roll Dice 51 times. Count the rows (or run the cat command and count the objects). There should be exactly 50, and the first roll you made should be gone. This is tedious but tests the real code.
Option 2: Temporarily lower the limit.
- In
HistoryStore.swift, changestatic let maximumCount = 50tostatic let maximumCount = 3. - Run, clear, and roll five times.
- Expected: exactly three rows, showing your three most recent rolls. Stop and Run again; still three.
- Change it back to
50and build. Do not commit the temporary value.
The limit is temporarily 3. The history contains three rolls with totals [9, 5, 12] (index 0 is newest). You roll a total of 7. Write down the contents of history after insert(roll, at: 0), then after the if block, and say which total was dropped.
Expected Results
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 this chapter the app looks exactly like Chapter 8. The difference is behavior over time.
There is no new screenshot for this chapter: the screen is the same as the Chapter 8 history screen. After rolling, stopping, and relaunching, you should see something like this:
Illustrative mockup — not a screenshot
Dice Foundry
[ D4 ] [ D6 ] [ D8 ]
[ D10] [ D12] [ D20]
Number of dice: 1 [ - | + ] <- controls reset after relaunch
Modifier: 0 [ - | + ]
2D20 + 3 <- restored from history.first
( 27 )
[ 17 ] [ 7 ]
Dice 24, modifier +3
[ Roll Dice ]
History Clear
2D20 + 3 27
17, 7 10:42 AM
-----------------------------------
2D20 + 3 15
...
Checklist of expected behavior:
- First launch (no file): "Tap Roll Dice to begin" and "No rolls yet". No error in the console.
- After rolls and a relaunch (from Xcode or the Home Screen): the same history, newest first; the result area shows the newest roll.
- After Clear and a relaunch: empty history and "Tap Roll Dice to begin".
- Never more than 50 rows.
roll-history.jsonexists in the app's Documents directory and contains a JSON array.
Reading This Like a Developer
Where execution begins. As before, iOS starts the process, @main DiceFoundryApp creates a WindowGroup containing ContentView. New in this chapter: when ContentView appears, the .onAppear closure runs loadHistory(). That is the first code to touch the disk.
Where persistent data comes from. At launch, history starts as [] (its @State initial value) and then loadHistory() replaces it with what store.load() returns. latestRoll starts as nil and is then set to history.first. So the values on screen after launch originate in roll-history.json, flow through Data(contentsOf:) and JSONDecoder, and land in @State.
Which code runs when each button is pressed.
| Action | Code path | Disk effect |
|---|---|---|
| Roll Dice | performRoll() → insert → trim → saveHistory() |
File rewritten with new list |
| Clear | clearHistory() → removeAll() → saveHistory() |
File rewritten as [] |
| Die button, Steppers | Change @State only |
None |
Where data is saved. Only in HistoryStore.save(_:), which is called only from saveHistory(). That single path is valuable: if saving ever misbehaves, there is one place to put a breakpoint.
How errors are handled. HistoryStore reports errors by throwing; it never prints. ContentView catches them in loadHistory() and saveHistory() and prints a message. The app keeps running either way. A missing file is not an error at all; load() returns [].
Presentation versus storage. ContentView decides when to load and save and what to do on failure. HistoryStore knows where the file is and how it is formatted. RollResult and DieType know nothing about files; they only declare that they are Codable. If you switched to SwiftData one day, you would rewrite HistoryStore and the two model types, but the view's buttons would not change. Chapter 13 separates these responsibilities further.
On a brand-new install, the app launches and you immediately tap Roll Dice once (D6, 1 die, modifier 0) and get a 4. Trace the following: what does store.load() return during .onAppear, and why does it not throw? What is latestRoll after loadHistory()? After the roll, how many elements does the JSON array in the file contain, and what is the value of its "dieType" field?
Troubleshooting
The type does not conform to Decodable or Encodable
Type 'RollResult' does not conform to protocol 'Decodable'
Type 'RollResult' does not conform to protocol 'Encodable'
Meaning: the compiler cannot generate Codable for RollResult because one of its stored properties is not Codable.
Likely cause: you added Codable to RollResult but not to DieType (Step 1). The message may also mention that DieType does not conform.
Investigate: check every stored property's type. Click the error to see Xcode's notes, which usually name the offending property. Add Codable to DieType.
"Cannot find 'HistoryStore' in scope"
Cannot find 'HistoryStore' in scope
Likely causes: the file was not created, the struct name is misspelled (Swift is case-sensitive: Historystore is a different name), or the file was created without the DiceFoundry target checked.
Investigate: select HistoryStore.swift in the Project navigator, open the File inspector (⌥⌘1), and make sure Target Membership includes DiceFoundry.
"Call can throw but is not marked with 'try'"
Call can throw but is not marked with 'try'
Meaning: you called store.load(), store.save(...), Data(contentsOf:), decode, encode or write without try.
Fix: add try in front of the call. If the call is in a function that does not throw, it must also be inside a do block with a catch. A related message, similar to "Errors thrown from here are not handled", means you used try outside a do block in a non-throwing function.
History does not survive a relaunch
Likely causes and checks:
.onAppear { loadHistory() }is missing or attached to the wrong view. Put aprint("loading")inloadHistory()and check the console at launch.saveHistory()is not called inperformRoll(). Run thecatcommand from Step 12 after a roll; if the file is unchanged, the save is not happening.- You are looking at a different simulator from the one you rolled on. Each simulator has its own sandbox.
- You deleted the app between runs, which deletes its data.
Cleared history comes back after relaunch
Cause: the Clear button still calls history.removeAll() directly, or clearHistory() does not call saveHistory(). Memory was cleared; the file was not. Check Steps 7 and 8.
A decoding error in the console at launch
You may see a message similar to:
Could not load roll history: DecodingError.dataCorrupted: Data was corrupted. Debug description: The given data was not valid JSON. ...
Older iOS runtimes (for example an iOS 17 simulator) may print the same error in a longer form beginning dataCorrupted(Swift.DecodingError.Context(. A different failure prints a message naming keyNotFound and the missing key, for example modifier.
Meaning: the file exists but does not match the format RollResult expects. The first means the bytes are not valid JSON (truncated or edited by hand). The second means a field is missing, which happens if you change a stored property's name or add a new non-optional stored property after files have been saved in the old format.
Investigate: cat the file (Step 12) and compare its fields with RollResult's stored properties. During development the simplest fix is to delete the app from the simulator, which deletes the old file. In a shipped app, changing a stored model needs more care (default values, optional new fields, or a custom decoder), because real users have old files on their devices.
You can see the corrupt-file path for yourself: run the app, then in Terminal overwrite the file with junk using echo "not json" > "$(xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data)/Documents/roll-history.json" (with your bundle identifier). Stop and Run. The console prints a decoding error and the app starts with an empty history. Roll once, and the file is replaced with valid JSON.
The preview shows different history from the simulator
Meaning: previews run in their own environment with their own sandbox. .onAppear runs in the preview too, but it reads the preview's file, not the simulator's. This is expected. Rely on the simulator when testing persistence.
Simulator menu items for the app switcher are not where described
Simulator menus vary between versions. Look in the Device menu for App Switcher and Home, or use the swipe-up gesture from the bottom of the simulated screen. The goal is simply to terminate the app without Xcode.
Knowledge Check
- What is the difference between volatile and persistent data? Give one example of each from Dice Foundry after this chapter.
- Why does
HistoryStore.load()return an empty array when the file does not exist, but throw when the file exists and cannot be decoded? - What does
options: .atomicprotect against, and how does it do so? - Why is a JSON file in the Documents directory a better fit for Dice Foundry's roll history than
UserDefaults? When would SwiftData be the better choice? - Why is
maximumCountdeclaredstatic, and why doesperformRoll()remove the last element when the history is over the limit?
Independent Challenge
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.
Make the history file easier to read when you inspect it with cat: each roll on its own lines, indented, with the keys in a consistent alphabetical order. Change only HistoryStore.swift. Acceptance criteria: the app still loads previously saved files; after a roll, cat shows indented, multi-line JSON with keys in alphabetical order; Stop and Run still restores the history.
If the history file is corrupt, the app currently prints to the console, which the user never sees. Show a short message in the History section, such as "Saved history could not be loaded.", when loading fails. Requirements: use a new @State property; set it in the catch of loadHistory(); remove the message once the history has been saved successfully (the next roll replaces the bad file); style it as red text. Acceptance criteria: with a valid file or no file, no message appears; after replacing the file with junk (see the Troubleshooting tip) and relaunching, the message appears; after the next roll, it disappears and does not return on relaunch.
Progressive hints are in the Chapter 9 Exercises document. Work on a Git branch so your main project stays identical to the reference.
Chapter Completion Checklist
DieTypeandRollResultconform toCodable.HistoryStore.swiftexists withmaximumCount,fileURL,init,load()andsave(_:).ContentViewhaslet store = HistoryStore(),clearHistory(),loadHistory()andsaveHistory().- The Clear button calls
clearHistory(). performRoll()trims toHistoryStore.maximumCountand callssaveHistory()..onAppear { loadHistory() }is attached to theScrollView.- Test A (Stop and Run) passes.
- Test B (app switcher, Home Screen relaunch) passes.
- Test C (Clear survives relaunch) passes.
- You viewed
roll-history.jsonwithxcrun simctl get_app_containerandcat. - You verified the 50-roll limit (and restored
maximumCountto 50 if you lowered it). - You can explain when you would choose
UserDefaults, a file, or SwiftData. - The project builds with no errors or warnings.
Development Checkpoint
Commit your work so you can return to this point.
In Xcode: Integrate → Commit... (the menu may be named Source Control in some versions), select all changed files, enter the message below, and commit. Or in Terminal, from your project folder:
git add -A
git commit -m "Chapter 9: Persist roll history as JSON"
git tag chapter-09
Make sure maximumCount is 50 before you commit.
To compare with the reference, open Reference-Checkpoints/Checkpoint-09-Persistence/DiceFoundry/ and compare HistoryStore.swift, ContentView.swift, DieType.swift and RollResult.swift with yours. You can use FileMerge (Xcode → Open Developer Tool → FileMerge) or Terminal:
diff -u Reference-Checkpoints/Checkpoint-09-Persistence/DiceFoundry/ContentView.swift \
/path/to/your/DiceFoundry/DiceFoundry/ContentView.swift
Differences in comments or the file header are fine. Differences in code are worth understanding.
Prediction Answers
Trace the trim. Before the roll, history totals are [9, 5, 12]. After insert(roll, at: 0): [7, 9, 5, 12] (four items). The if sees 4 > 3, so removeLast() removes 12, the oldest roll. Result: [7, 9, 5]. The newest three remain.
First launch, then a roll. During .onAppear, store.load() finds no file, so fileExists is false, !false is true, and it returns [] before reaching any try line. Nothing throws. latestRoll becomes [].first, which is nil, so the screen shows "Tap Roll Dice to begin". After the roll, history has one element and saveHistory() writes a JSON array with one object. Its "dieType" field is 6, the raw value of .d6, because raw-value enums encode as their raw value.