Chapter 8 — Structures and Data Models
At the end of Chapter 7, one roll is described by three separate state properties: results, rolledModifier and rolledNotation. They only make sense together, they must be updated together, and nothing in the code says that they belong together. That works for one roll. It does not work for a history of rolls: you would need three parallel arrays and a lot of discipline to keep them lined up. In this chapter you create a data model: a Swift structure named RollResult that captures everything about one completed roll in a single value. The roll's die type, dice values, modifier, a unique identifier and the time it happened become one record, and the subtotal, total, notation and a printable list of values are calculated from that record. With that model in place, a roll history is simply an array of RollResult values, and displaying it is a ForEach. By the end, Dice Foundry shows the newest roll at the top of a scrolling history with notation, individual dice, total and time, and a Clear button empties it.
Learning Objectives
By the end of this chapter you will be able to:
- Explain what a data model is and why one completed roll should be a single structured value rather than several unrelated variables.
- Declare a
structwith stored properties, and explain the difference between stored and computed properties. - Explain the memberwise initializer Swift generates for a structure, and write a custom initializer with default parameter values when the generated one is not convenient.
- Use
self.to distinguish a property from a parameter with the same name. - Explain value semantics: what happens when a structure is assigned or placed in an array, and why that is useful for records.
- Use
UUIDto give each value a unique identity andDateto record when it was created. - Make your own type conform to the
Identifiableprotocol and explain what that enables inForEach. - Store an array of custom structures in
@State, insert new items at the front, and remove all items. - Transform an array with
mapand combine strings withjoined(separator:). - Format a
Datefor display. - Use an optional state property (
RollResult?) andif letto show content only when a value exists. - Build a scrolling page with
ScrollView, and explain when to useListinstead and why aListshould not be nested inside aScrollView. - Disable a button based on a Boolean expression with
.disabled.
Concept Explanation
From loose variables to a record
Look at how Chapter 7 describes the worked example roll (3D6 + 2, dice 4, 2, 6):
results = [4, 2, 6] @State in ContentView
rolledModifier = 2 @State in ContentView
rolledNotation = "3D6 + 2" @State in ContentView
subtotal = 12 computed property of ContentView
total = 14 computed property of ContentView
Five names, spread across a view whose real job is layout. Nothing groups them. If you forget to assign one of them in performRoll(), they silently disagree. And to keep a history, you would need [[Int]] for all the results, [Int] for all the modifiers, [String] for all the notations, and you would have to make sure index 7 in one array always matches index 7 in the others. That is fragile.
The fix is to describe the thing you care about, one completed dice roll, as a type of its own. In Swift that is a struct:
RollResult
id UUID a unique identity for this roll
dieType DieType .d6
values [Int] [4, 2, 6]
modifier Int 2
date Date when it was rolled
subtotal Int 12 (calculated from values)
total Int 14 (subtotal + modifier)
notation String "3D6 + 2" (calculated from values, dieType, modifier)
valuesDescription String "4, 2, 6"
Now one roll is one value. You can store it in one @State property, put it in an array, pass it to a function, and (in Chapter 9) save it to a file. Every piece of information about the roll travels together, and the calculations travel with the data they are calculated from.
A type designed to represent the information your app works with, independent of how it is displayed, is called a data model (or simply a model). DieType from Chapter 5 was your first model. RollResult is the first one that holds several pieces of data.
Imagine a deployment script that tracks the last deployment in three environment variables: LAST_VERSION, LAST_HOST and LAST_TIME. It works until two deployments overlap, or someone updates one variable and not the others. The robust version writes a single structured record (a row, or a JSON object) per deployment, and the deployment history is a list of those records. RollResult is that record for a dice roll, and history is the list.
Structures, revisited
You have been writing structures since Chapter 3: ContentView is a struct that conforms to View. Until now you used struct mainly as "the thing SwiftUI wants". Now you will use it for its main purpose: grouping related data into a new type.
A structure declaration lists the data it holds as properties:
struct RollResult {
let dieType: DieType
let values: [Int]
let modifier: Int
}
Each let line declares a stored property: a named slot that holds a value inside every RollResult. Once you have a RollResult named roll, you read its properties with dot syntax: roll.values, roll.modifier, exactly as you have read selectedDie.sides and results.count.
Using let for these properties makes a RollResult immutable: once created, its values cannot change. That is the right choice for a record of something that already happened. A roll that was 3D6 + 2 with dice 4, 2, 6 will always have been that roll. If you want a different roll, you create a new value.
Stored and computed properties
A stored property holds data. A computed property calculates a value each time it is read, from other properties. You wrote computed properties in Chapter 5 (DieType.name) and Chapter 6 (total). In a model they are especially valuable:
var subtotal: Int {
values.reduce(0, +)
}
var total: Int {
subtotal + modifier
}
Why not store subtotal and total as well? Because then the same fact would be stored twice, once implicitly in values and modifier and once in total, and two copies of a fact can disagree. A computed property cannot disagree with the data it is calculated from. This principle is often called having a single source of truth. The calculation is trivial for a handful of numbers, so there is no performance reason to store it.
Rule of thumb: store what you cannot recalculate (the dice values, the modifier, the time); compute everything else.
If you have designed database schemas, this is normalization: do not store a derived column that can drift from its source. If you have managed configuration, it is the difference between a template that derives a URL from a hostname and a file where someone typed both and later changed only one.
Initializers
To create a value of a structure, you call an initializer. Its job is to give every stored property a value before anyone can use the new instance. Swift never lets you read an uninitialized property.
The memberwise initializer
If you do not write an initializer yourself, Swift generates one for every structure: the memberwise initializer. It has one parameter per stored property, in declaration order, with the property names as labels. For the five stored properties RollResult will have, the generated initializer would be called like this:
let roll = RollResult(
id: UUID(),
dieType: .d6,
values: [4, 2, 6],
modifier: 2,
date: Date()
)
That is free and perfectly correct, and many structures never need anything else. But look at what every caller must now do. Every time code creates a roll, it must remember to generate a new identifier and capture the current time. Those are not decisions the caller should be making: in the app, a new roll always gets a new identifier and always happens now. Repeating id: UUID(), ... date: Date() at every call site is noise at best, and at worst invites a bug such as copying an id from another roll.
A custom initializer with default parameter values
You can write your own initializer with the keyword init. Swift lets any function parameter, including an initializer's, have a default value: if the caller omits that argument, the default is used.
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
self.id = id
self.dieType = dieType
self.values = values
self.modifier = modifier
self.date = date
}
Now the everyday call is short and says only what matters:
let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
The default expressions UUID() and Date() are evaluated each time the initializer is called without those arguments, so every roll gets its own fresh identifier and its own timestamp. You can still pass them explicitly when you need to, and you will need to later: in Chapter 12, tests create rolls with a fixed date so the results are predictable.
Three details:
- The parameters with defaults are placed last. That is a Swift convention, and it keeps calls readable: required information first, optional information after.
- Inside the initializer, the parameter
idand the propertyidhave the same name. A bareidmeans the parameter (the closest declaration wins).self.idmeans "theidproperty of the instance being created". Soself.id = idreads: "set myidproperty to the value of theidparameter". You will see this pattern in almost every hand-written initializer. - When you write your own
initinside a structure, Swift no longer generates the memberwise initializer. Your initializer is now the only way to create aRollResult, which is exactly what you want: there is one entry point, and it always fills in an identifier and a date.
Value types and copy semantics
Structures in Swift are value types. Assigning a structure to another variable, passing it to a function, or putting it into an array produces an independent copy. Changing one copy never changes another. Int, String, Array and Date are value types too; that is why, in Chapter 7, copying modifier into rolledModifier worked as a snapshot.
struct Counter {
var count = 0
}
var a = Counter()
var b = a // b is a copy of a
b.count = 10
print(a.count) // 0 - a was not affected
print(b.count) // 10
For a roll history this is exactly what you want. When performRoll() puts a roll into latestRoll and also into history, those are two copies of the same immutable data. Nothing that happens to one can corrupt the other, and no other part of the app can reach into the history and change a past roll.
The alternative, a reference type (a class), works differently: several variables can refer to the same single instance, and a change through one is visible through all of them. You will meet classes in Chapter 13, where shared, changing state is what you want. For records of things that happened, value types are the natural fit.
A value type behaves like copying a file: cp report.txt backup.txt, then editing backup.txt leaves report.txt untouched. A reference type behaves like a symbolic link: two names, one file, and an edit through either name changes the one underlying file.
Unique identity: UUID
Two rolls can contain exactly the same data. Roll 1D6 twice and get 4 both times, within the same minute: the die, values and modifier are identical. They are still two different events. To tell them apart, each roll needs an identity that has nothing to do with its contents.
UUID (Universally Unique Identifier) is a type from Foundation that holds a 128-bit random value. Calling UUID() creates a new one, usually shown as text like E621E1F8-C36C-495A-93FC-0C247A3E6E5F. The chance of two randomly generated UUIDs colliding is so small that software everywhere treats them as unique. You have very likely seen UUIDs as disk and partition identifiers, VM identifiers, or request IDs in logs.
Why not use something simpler?
| Candidate identity | Problem |
|---|---|
| The array index | Changes whenever a roll is inserted at the front; the roll at index 0 is a different roll after every tap |
| The date | Two rolls can happen within the same instant as far as display goes, and dates are not guaranteed unique |
| The notation or total | Many different rolls share them |
| A counter (1, 2, 3...) | Workable, but someone must store and increment it, and it restarts when the app restarts unless you save it too |
UUID() |
Unique, needs no coordination, never changes for the life of the value |
Date
Date is Foundation's type for a single point in time. Date() means "now". Internally it stores a number of seconds relative to a fixed reference moment, independent of time zone or calendar. Time zones, 12- or 24-hour clocks and languages only come into play when you format a date for a person to read, and Swift does that formatting for you according to the user's device settings:
let now = Date()
now.formatted(date: .omitted, time: .shortened) // "2:05 PM" (or "14:05")
now.formatted(date: .abbreviated, time: .omitted) // "Dec 5, 2026"
now.formatted(date: .numeric, time: .shortened) // "12/5/2026, 2:05 PM"
now.formatted() // date and time, default style
The exact output depends on the region and language settings of the device or simulator, which is the point: you describe which parts you want and how detailed, and the system chooses the correct local format. Dice Foundry shows only the time, because a history of a gaming session is read within the same day.
This is the same rule you follow for logs: store timestamps in a zone-independent form, convert to local time only for display. A Date is the stored form; formatted(...) is the rendering.
Protocols and Identifiable
A protocol is a named list of requirements: "any type that claims to be X must provide these properties or methods". When a type declares that it conforms (struct ContentView: View), the compiler checks that it really does provide them. You have used this since Chapter 3, and in Chapter 5 you made DieType conform to Identifiable and CaseIterable.
Identifiable has one requirement: a property named id whose type can be compared for equality and hashed (used as a lookup key). UUID qualifies. By declaring
struct RollResult: Identifiable {
let id: UUID
...
}
you promise that every RollResult has a stable, unique id. ForEach relies on that promise. When the history array changes, SwiftUI uses the ids to work out which rows are new, which were removed and which merely moved, so it can update the screen correctly (and animate it well when you add animation in Chapter 11). That is why you can write ForEach(history) with no id: argument, while Chapter 6's dice chips needed ForEach(results.indices, id: \.self): plain Int values have no identity of their own, so you had to tell ForEach what to use.
A protocol is like a storage driver interface. The volume manager does not care which vendor's driver it talks to, only that the driver implements attach, detach and status. ForEach does not care what your type is, only that it implements id.
Arrays of custom structures
An array can hold any type, including your own. [RollResult] is "an array of roll results", and everything you learned about arrays in Chapter 6 applies: count, isEmpty, indexing, append, removeAll(). Two operations are new in this chapter:
history.insert(roll, at: 0)puts a new element at the given index, shifting everything after it one place to the right. Inserting at index 0 puts the newest roll first, which is the order a history should be read in. (Withappendthe newest roll would be at the bottom, and the user would have to scroll to see it.)mapcreates a new array by applying a transformation to every element.
Transforming data with map and joined
valuesDescription turns [4, 2, 6] into the text "4, 2, 6". That takes two steps:
[4, 2, 6] an [Int]
.map { String($0) }
["4", "2", "6"] a [String]
.joined(separator: ", ")
"4, 2, 6" a String
map takes a closure and calls it once for each element, collecting the results into a new array. The closure here converts an Int to a String with String(...), a conversion like the Double(rolls) you used in Chapter 2.
The closure is written with a shorthand you have not seen yet: $0 means "the closure's first parameter", in this case the current element. These two lines are equivalent:
values.map { value in String(value) }
values.map { String($0) }
The short form is very common in Swift code, including AI-generated code; Chapter 14 covers $0 in more detail. For now, read { String($0) } as "turn each element into a string".
joined(separator:) is available on arrays of strings. It concatenates the elements, inserting the separator between them (not before the first or after the last).
You may wonder why not write "\(values)". Interpolating an array produces "[4, 2, 6]", with brackets: programmer formatting, not user formatting. Formatting data deliberately for people is part of building an interface.
Optional state: there may be no latest roll
Before the first roll there is no latest roll. Chapter 7 represented "nothing yet" with an empty results array and used meaningless initial values for rolledModifier and rolledNotation. With a model, Swift has a precise way to say "a roll, or nothing": an optional, which you met in Chapter 2.
@State private var latestRoll: RollResult?
The ? makes the type "RollResult or nil". An optional property declared with var and no initial value starts as nil. To use the roll inside it, unwrap it with if let:
if let roll = latestRoll {
// roll is a plain RollResult here
} else {
// latestRoll is nil
}
Inside body, this is a conditional view, like the if / else in Chapter 7, with the bonus that the unwrapped roll is available to every view in the first block. There are no more meaningless placeholder values: either there is a complete roll, or there is nothing.
Scrolling: ScrollView, ForEach and List
A history grows. After a dozen rolls it no longer fits on the screen, so the screen must scroll. SwiftUI offers two common approaches.
List is a ready-made scrolling list of rows, with system styling (separators, insets, grouped backgrounds), cell reuse for very long lists, and built-in support for features such as swipe-to-delete:
List(history) { roll in
HStack {
Text(roll.notation)
Spacer()
Text("\(roll.total)")
}
}
A List is the right choice when the list is the screen, for example a mail inbox or a settings page.
ScrollView makes whatever it contains scrollable. Inside it you lay out views as usual, using VStack and ForEach for repeated rows. It has no built-in row styling; you decide how everything looks.
Dice Foundry's screen is one page: the dice picker, the steppers, the result, the Roll button and the history, in that order. The whole page should scroll as one, so that the history can use all the space below the controls. That is a ScrollView around the page's VStack, with the history rows drawn by ForEach inside it.
Why not put a List for the history inside that ScrollView? A List is itself a scrolling container. Nesting one scrolling container inside another in the same direction gives SwiftUI two conflicting ideas of height: the outer ScrollView offers its content unlimited height, and a List has no natural height of its own. The usual result is a List that collapses to a tiny or zero height, or a small separately scrolling box inside the page. It is one of the most common SwiftUI layout bugs, and AI assistants generate it often. Use one scrolling container per direction: either the whole screen is a List, or the whole screen is a ScrollView with ForEach rows.
A note on cost: a ForEach inside a plain VStack creates all of its rows at once. For a history that will be limited to 50 entries in Chapter 9, that is no problem. For thousands of rows you would use a List or a LazyVStack, which create rows only as they scroll into view.
Why the Spacers go away
In Chapters 3 to 7, two Spacer views pushed the result into the middle of the screen and the Roll button to the bottom. A Spacer expands to fill available space. Inside a ScrollView, the content is offered unlimited vertical space, so "fill the remaining space" has no meaning; spacers in a vertical scroll view collapse to their minimum size. The layout must instead be described by the content itself: fixed spacing between sections, and a fixed height for the placeholder so the screen does not jump when the first result appears.
Disabling a control
Any SwiftUI control can be disabled with the .disabled(_:) modifier, which takes a Bool. When the value is true, the control is drawn dimmed and ignores taps. Because the argument is a Boolean expression evaluated on every render, the control enables and disables itself as state changes:
Button("Clear") {
history.removeAll()
}
.disabled(history.isEmpty)
An empty history cannot be cleared, so the button is unavailable until there is something to clear. This is both a usability improvement (the interface shows what is possible) and a small piece of validation, like the Stepper bounds in Chapter 7.
Syntax Breakdown
A structure that conforms to a protocol
struct RollResult: Identifiable {
let id: UUID
let dieType: DieType
let values: [Int]
let modifier: Int
let date: Date
| Token | Meaning |
|---|---|
struct |
Declares a new value type |
RollResult |
The type's name; type names start with a capital letter |
: Identifiable |
Declares conformance to the Identifiable protocol; the compiler checks that an id property exists |
let id: UUID |
A stored, constant property named id of type UUID; it satisfies Identifiable |
let dieType: DieType |
Your own enum from Chapter 5, used as a property type |
let values: [Int] |
The individual dice results |
let modifier: Int |
The modifier applied to this roll |
let date: Date |
When the roll happened |
No property has an initial value here. That is allowed in a structure, as long as an initializer gives each one a value.
A custom initializer
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
self.id = id
self.dieType = dieType
| Token | Meaning |
|---|---|
init |
Declares an initializer. No func, no name, no return type: an initializer always produces an instance of its own type. |
dieType: DieType, values: [Int], modifier: Int |
Required parameters; their names are also their argument labels |
id: UUID = UUID() |
A parameter with a default value. If the caller leaves it out, UUID() is called to make a new identifier. |
date: Date = Date() |
Likewise; defaults to the current time |
self.id |
The id property of the instance being initialized |
= id |
The value of the id parameter |
A computed property in a model
var subtotal: Int {
values.reduce(0, +)
}
This is the same form you used in ContentView in Chapters 6 and 7, now inside the model, where it reads the model's own values. Computed properties are always declared with var (even though you cannot assign to them), because their value can differ from one read to the next if the underlying data changes.
map, $0 and joined
values.map { String($0) }.joined(separator: ", ")
| Token | Meaning |
|---|---|
values |
The [Int] property |
.map |
Method on arrays: build a new array by transforming each element |
{ String($0) } |
A closure passed with trailing-closure syntax; $0 is shorthand for its first (and only) parameter, the current element |
String(...) |
Converts the Int to its text form, 4 → "4" |
.joined(separator: ", ") |
Called on the resulting [String]; concatenates the elements with ", " between them |
Calls like this, where each method is called on the result of the previous one, are called method chaining. Read them left to right as a pipeline, like a shell pipe.
Optional state
@State private var latestRoll: RollResult?
| Token | Meaning |
|---|---|
@State private var |
Same as all the other view state |
latestRoll |
The most recent roll, if there is one |
: RollResult? |
An optional RollResult: either a roll or nil |
(no = ...) |
An optional var without an initial value starts as nil |
if let in a view
if let roll = latestRoll {
Text(roll.notation)
| Token | Meaning |
|---|---|
if let |
Optional binding: test whether the optional contains a value and, if it does, give that value a name |
roll |
The new, non-optional constant, available only inside the braces |
= latestRoll |
The optional being unwrapped |
roll.notation |
Reading a computed property of the unwrapped model |
An array of structures in state, and insert
@State private var history: [RollResult] = []
history.insert(roll, at: 0)
| Token | Meaning |
|---|---|
[RollResult] |
Array whose elements are RollResult values |
= [] |
Starts empty |
history.insert( |
Array method that adds an element at a position |
roll |
The element to add (a copy is stored) |
at: 0 |
The index to insert at; 0 is the front, so existing elements shift down by one |
ForEach over identifiable values
ForEach(history) { roll in
| Token | Meaning |
|---|---|
ForEach(history) |
Create views for each element of history. No id: parameter is needed because RollResult is Identifiable. |
{ roll in |
A closure called once per element; roll is that element |
Date formatting
Text(roll.date.formatted(date: .omitted, time: .shortened))
| Token | Meaning |
|---|---|
roll.date |
The stored Date |
.formatted( |
Method on Date that produces a String for display, using the device's locale |
date: .omitted |
Do not include the calendar date |
time: .shortened |
Include the time, hours and minutes only |
Scroll view, divider and disabled
ScrollView {
VStack(spacing: 20) {
Divider()
.disabled(history.isEmpty)
| Token | Meaning |
|---|---|
ScrollView { ... } |
A container whose content can scroll (vertically by default) when it is taller than the screen |
Divider() |
A thin horizontal line, used here to separate history rows |
.disabled(history.isEmpty) |
Disables the button whenever the Boolean expression is true |
VStack(alignment: .leading, spacing: 12) |
A vertical stack that aligns its children to the leading edge (the left, in left-to-right languages) instead of the center |
Guided Implementation
This chapter has two parts. First you create the RollResult model in its own file and try it out. Then you change ContentView to use it, add the scrolling layout, and build the history section. The project builds after every step; one step (Step 9) temporarily stops the result from appearing, and the step tells you so.
Step 1 — Create RollResult.swift
File: new file RollResult.swift · Where: the DiceFoundry group, next to DieType.swift · Action: Create file
- In the Project navigator (⌘0 if it is hidden), select
DieType.swift, so the new file is created in the same group. - Choose File → New → File from Template… (⌘N). In some Xcode versions the menu item is File → New → File….
- Choose iOS at the top, then Swift File, and click Next.
- Name it
RollResult. Make sure the DiceFoundry target is checked under Targets, and click Create.
Xcode creates the file with a comment header and import Foundation. Below the import, type:
struct RollResult: Identifiable {
let id: UUID
let dieType: DieType
let values: [Int]
let modifier: Int
let date: Date
}
What it does. Declares the new type with five stored properties: the identity, the die that was rolled, the individual dice values, the modifier, and when it happened.
Why it is written this way.
- It needs
import Foundation(already there) becauseUUIDandDatecome from Foundation, not from the Swift language itself.DieType.swifthas the same import. - Every property is
let: a roll is a record of something that happened and must not change afterward. - There is no
quantityproperty. The number of dice isvalues.count; storing it as well would create a second source of truth that could disagree. - There is no
subtotal,totalornotationstored either. You will compute them in Steps 3 and 4. Identifiableis satisfied bylet id: UUID.
What should happen. Build (⌘B). It succeeds. Swift has generated a memberwise initializer for you, invisibly.
Step 2 — Add an initializer with default values
Look at the memberwise initializer you just got for free. To create the worked-example roll with it you would write:
let roll = RollResult(
id: UUID(),
dieType: .d6,
values: [4, 2, 6],
modifier: 2,
date: Date()
)
Every caller in the app would have to remember id: UUID() and date: Date(). Replace that burden with an initializer that supplies them by default.
File: RollResult.swift · Where: inside struct RollResult, after let date: Date and before the struct's closing brace, separated by a blank line · Action: Add
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
self.id = id
self.dieType = dieType
self.values = values
self.modifier = modifier
self.date = date
}
What it does. Defines the one way to create a RollResult. Callers must provide the die, values and modifier. If they do not provide an id or date, a new UUID and the current time are used.
Why it is written this way.
- Required parameters come first and defaulted ones last, so the everyday call is
RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2). - Keeping
idanddateas parameters, rather than assigningUUID()andDate()directly inside the body, leaves a door open: tests (Chapter 12) and loading saved rolls can supply exact values. - Each line
self.x = xcopies a parameter into the property of the same name. Every stored property must be assigned before the initializer ends; if you forget one, the compiler reports that the property is not initialized. - The first line is long (about 95 characters). It is kept on one line to match the reference project exactly; Swift would also accept the parameters split across several lines.
What should happen. Build (⌘B). It succeeds. The memberwise initializer no longer exists; this one replaces it.
Step 3 — Add the subtotal and total
File: RollResult.swift · Where: inside struct RollResult, after the closing brace of init, separated by a blank line · Action: Add
var subtotal: Int {
values.reduce(0, +)
}
var total: Int {
subtotal + modifier
}
What it does. subtotal adds the dice values; total adds the modifier to the subtotal.
Why it is written this way. This is the same logic as Chapter 7's ContentView, but now it lives next to the data it calculates from. Notice total uses the roll's own modifier, the one stored when the roll was created. The Chapter 7 bug (a total that follows the live control) cannot happen here: a RollResult does not know the controls exist.
What should happen. Build. It succeeds.
Step 4 — Add dice notation
File: RollResult.swift · Where: after the closing brace of total · Action: Add
var notation: String {
let dice = "\(values.count)\(dieType.name)"
if modifier > 0 {
return "\(dice) + \(modifier)"
} else if modifier < 0 {
return "\(dice) - \(abs(modifier))"
} else {
return dice
}
}
What it does. Produces "3D6 + 2", "2D20 - 4" or "1D8" for this roll.
Why it is written this way. It is Chapter 7's notation(quantity:dieType:modifier:) function turned into a computed property. A function needed three parameters because it lived in the view and had to be told about the roll. The property lives inside the roll, so it reads values, dieType and modifier directly. The quantity comes from values.count: the number of dice actually rolled, which can never disagree with the values shown.
A computed property can contain several statements and returns, as this one does. The single-expression form without return (as in subtotal) is just a shortcut for one-line bodies.
What should happen. Build. It succeeds.
Step 5 — Describe the values as text
File: RollResult.swift · Where: after the closing brace of notation, before the struct's closing brace · Action: Add
var valuesDescription: String {
values.map { String($0) }.joined(separator: ", ")
}
What it does. Turns [4, 2, 6] into "4, 2, 6" for the history rows.
Why it is written this way. map converts each number to a string, and joined combines the strings with a comma and space between them. Writing "\(values)" would show brackets. Making this a property of the model means every view that ever needs the text form of the values gets the same formatting.
What should happen. Build. It succeeds. Your RollResult.swift is complete. Compare it with Reference-Checkpoints/Checkpoint-08-Roll-History/DiceFoundry/RollResult.swift if you want to check it now.
For reference, this is the complete RollResult.swift at the end of this step:
//
// RollResult.swift
// DiceFoundry
//
import Foundation
struct RollResult: Identifiable {
let id: UUID
let dieType: DieType
let values: [Int]
let modifier: Int
let date: Date
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
self.id = id
self.dieType = dieType
self.values = values
self.modifier = modifier
self.date = date
}
var subtotal: Int {
values.reduce(0, +)
}
var total: Int {
subtotal + modifier
}
var notation: String {
let dice = "\(values.count)\(dieType.name)"
if modifier > 0 {
return "\(dice) + \(modifier)"
} else if modifier < 0 {
return "\(dice) - \(abs(modifier))"
} else {
return dice
}
}
var valuesDescription: String {
values.map { String($0) }.joined(separator: ", ")
}
}
Step 6 — Try the model in a playground
Before wiring the model into the interface, experiment with it on its own, as you did with plain values in Chapter 2. This is optional but strongly recommended: it is the fastest way to build an intuition for initializers and value types.
File: SwiftPractice.swift (from Chapter 2; if you deleted it, create a new Swift File named ModelPractice.swift and put import Playgrounds below import Foundation) · Where: at the end of the file · Action: Add (practice code; not part of the app)
#Playground("RollResult model") {
let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
print(roll.notation) // 3D6 + 2
print(roll.valuesDescription) // 4, 2, 6
print(roll.subtotal, roll.total)
print(roll.id)
print(roll.date.formatted(date: .omitted, time: .shortened))
let penalty = RollResult(dieType: .d20, values: [15, 7], modifier: -4)
print(penalty.notation, penalty.total)
}
#Playground("Value semantics") {
let first = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
var history = [first]
var backup = history
let second = RollResult(dieType: .d8, values: [5], modifier: 0)
history.insert(second, at: 0)
print(history.count, backup.count)
print(history[1].id == first.id)
backup.removeAll()
print(history.count)
}
Before running the "RollResult model" playground, predict what it prints for roll.subtotal, roll.total and for penalty.notation, penalty.total.
Open the canvas (⌥⌘↩) and select each playground tab to see its output, as in Chapter 2. If your Xcode does not show #Playground results, temporarily put the same lines inside performRoll() in ContentView (they are just print statements), run, tap Roll Dice, and read the console; then remove them.
Before you look at the output of the "Value semantics" playground, predict the three printed lines. Hint: backup = history copies the array, and the array holds copies of the rolls.
You can also try the following line. It will not compile. Read the error and explain it to yourself:
let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
roll.modifier = 3
The error is similar to "Cannot assign to property: 'modifier' is a 'let' constant". Records do not change.
When you are done experimenting, you can delete the playground blocks, or keep them for reference. The reference checkpoints do not include practice files.
Step 7 — Make the page scroll
Now switch to ContentView.swift. Before using the model, prepare the layout: the history will make the page taller than the screen, so the page must scroll.
File: ContentView.swift · Where: body · Action: Replace the outer structure as described below
Make these changes:
- On the line after
var body: some View {, typeScrollView {. - Change
VStack(spacing: 16) {toVStack(spacing: 20) {. - Delete both
Spacer()lines: the one below the modifierStepperand the one above the Roll Dice button. - At the bottom of
body, theVStack's closing brace is followed by.padding(). Leave.padding()attached to theVStack, and add a closing brace for theScrollViewafter it. - Select everything inside
bodyand press ⌃I to re-indent.
The outer shape of body is now:
var body: some View {
ScrollView {
VStack(spacing: 20) {
...
}
.padding()
}
}
(The ... stands for the title, die grid, steppers, result area and button, unchanged apart from being indented one more level.)
What it does. The whole page, from the title down to the button, now scrolls as a unit when it is taller than the screen.
Why it is written this way. One scrolling container for one page. .padding() stays on the VStack, inside the scroll view, so the content keeps its margins while the scrollable area still reaches the screen edges. The spacers are removed because, inside a vertical ScrollView, there is no leftover space for them to fill; spacing between sections now comes from VStack(spacing: 20).
What should happen. Run (⌘R). Everything works as before, but the layout is now packed toward the top of the screen rather than spread out, and the Roll Dice button sits directly below the result area. Roll 10 dice with a modifier: the page may now be tall enough to scroll slightly. This is expected; the history will fill the space below.
Step 8 — Add state for the latest roll and the history
File: ContentView.swift · Where: inside struct ContentView, directly below @State private var rolledNotation: String = "" · Action: Add
@State private var latestRoll: RollResult?
@State private var history: [RollResult] = []
What it does. latestRoll will hold the most recent roll, or nil before the first roll. history will hold every roll, newest first.
Why it is written this way. One optional property replaces three loose ones; one array of records holds the whole history. Both are @State because the screen displays them and must update when they change.
What should happen. Build. It succeeds. For a few steps, the old Chapter 7 properties and the new ones exist side by side; you will remove the old ones in Step 11.
Step 9 — Create a RollResult in performRoll()
File: ContentView.swift · Where: func performRoll() · Action: Replace the whole function with
func performRoll() {
if isValidQuantity(quantity) {
let values = rollDice(count: quantity, sides: selectedDie.sides)
let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
latestRoll = roll
history.insert(roll, at: 0)
} else {
print("Invalid quantity: \(quantity)")
}
}
What it does. After validating the quantity, it rolls the dice into a local constant values, packages the die, values and modifier into one RollResult, stores it as the latest roll, and inserts a copy at the front of the history.
Why it is written this way.
- This is still the only place where the controls (
selectedDie,quantity,modifier) become a roll. The snapshot idea from Chapter 7 is now built into the model: the initializer captures the values at this moment, and theletproperties guarantee they never change. valuesandrollare local constants (let), not state. They exist only while the function runs; what survives is what gets assigned to state.RollResult(dieType:values:modifier:)relies on the defaultidanddate. Every roll gets a fresh identifier and the current time without the caller thinking about it.latestRoll = rollandhistory.insert(roll, at: 0)store two independent copies of the same immutable value, which is safe because structures are value types.insert(..., at: 0)keeps the newest roll at the top of the history.
Suppose that, starting from an empty history, you roll three times and the totals are 5, then 9, then 2. Using history.insert(roll, at: 0), what are the totals of history[0], history[1] and history[2], and what is latestRoll?.total? What would the order be if the code used history.append(roll) instead?
What should happen. Build. It succeeds. If you run now, tapping Roll Dice appears to do nothing: the function no longer assigns results, and the result area still reads results. Step 10 fixes that.
Step 10 — Display the latest roll from the model
File: ContentView.swift · Where: inside body, the whole if results.isEmpty { ... } else { ... } block, between the modifier Stepper and the Button("Roll Dice") · Action: Replace with
if let roll = latestRoll {
Text(roll.notation)
.font(.title2)
.fontWeight(.semibold)
ZStack {
Circle()
.fill(Color.orange.opacity(0.2))
.frame(width: 140, height: 140)
Text("\(roll.total)")
.font(.system(size: 64, weight: .bold))
}
LazyVGrid(columns: resultColumns, spacing: 8) {
ForEach(roll.values.indices, id: \.self) { index in
Text("\(roll.values[index])")
.font(.title3)
.fontWeight(.semibold)
.frame(width: 44, height: 44)
.background(Color.orange.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
if roll.modifier != 0 {
Text("Dice \(roll.subtotal), modifier \(formattedModifier(roll.modifier))")
.foregroundStyle(.secondary)
}
} else {
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
.frame(height: 140)
}
What it does. If there is a latest roll, it unwraps it as roll and shows the roll's notation, total, chips and breakdown, all read from the model. Otherwise it shows the placeholder.
Why it is written this way.
- The order of the branches is reversed compared with Chapter 7: the "has a value" case comes first, because that is how
if letworks. - Every value in the result area now comes from
roll:roll.notation,roll.total,roll.values,roll.modifier,roll.subtotal. Nothing reads the controls, so the Chapter 7 bug is impossible by construction. - The placeholder gets
.frame(height: 140), the same height as the circle, so it reserves roughly the space a result will use. Without the spacers to absorb changes, this stops the Roll Dice button and history from jumping as much when the first result appears. - The dice chips still use
ForEach(roll.values.indices, id: \.self). Individual dice values have no identity of their own, and the whole array is replaced with each roll, so indices are a reasonable identity here. formattedModifierstill lives inContentView; it is presentation formatting, and in Chapter 10 it moves to a shared place.
What should happen. Run (⌘R). Rolling works again, exactly as in Chapter 7: notation, total, chips and breakdown, and changing controls after a roll does not change the result.
Step 11 — Remove the old Chapter 7 state
The view no longer needs the loose variables. Removing them proves that nothing still depends on them: if something did, the build would fail and tell you where.
File: ContentView.swift · Where: several places in struct ContentView, listed below · Action: Delete
Delete:
- The three state properties
@State private var results: [Int] = [],@State private var rolledModifier: Int = 0and@State private var rolledNotation: String = "". - The computed properties
var subtotal: Int { ... }andvar total: Int { ... }(abovebody). - The function
func sum(of values: [Int]) -> Int { ... }. - The function
func notation(quantity: Int, dieType: DieType, modifier: Int) -> String { ... }.
Your state properties now read:
@State private var selectedDie: DieType = .d6
@State private var quantity: Int = 1
@State private var modifier: Int = 0
@State private var latestRoll: RollResult?
@State private var history: [RollResult] = []
What it does. Removes duplicate logic and dead state. Summing and notation now exist in exactly one place, RollResult.
Why it is written this way. Leaving the old code in place would compile, but it would mislead the next reader (including you, in a month, or an AI assistant) into thinking it is used. Deleting dead code and letting the compiler confirm nothing depends on it is a safe, routine cleanup.
What should happen. Build (⌘B). It should succeed. If it fails with "Cannot find 'results' in scope" (or rolledModifier, subtotal, total), some code still uses the old names: the error points to the line. Compare that line with Step 10.
Step 12 — Add the history header and Clear button
File: ContentView.swift · Where: inside body, after the Roll Dice button's last modifier .tint(.orange), still inside VStack(spacing: 20) · Action: Add
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("History")
.font(.title2)
.fontWeight(.bold)
Spacer()
Button("Clear") {
history.removeAll()
}
.disabled(history.isEmpty)
}
if history.isEmpty {
Text("No rolls yet")
.foregroundStyle(.secondary)
}
}
What it does. Adds a "History" heading with a Clear button on the right, and a "No rolls yet" message while the history is empty.
Why it is written this way.
- A nested
VStack(alignment: .leading, ...)makes the history section left-aligned, while the rest of the page stays centered. - The
Spacer()inside theHStackpushes the Clear button to the trailing edge. ThisSpaceris fine inside a scroll view: it expands horizontally within a row of fixed width, not vertically. history.removeAll()empties the array. It does not touchlatestRoll: clearing the log does not erase the dice currently shown. That is a design choice; you could reasonably decide otherwise..disabled(history.isEmpty)greys out the button whenever there is nothing to clear.if history.isEmpty(with noelse) shows an empty-state message. Empty states that explain themselves are a mark of a finished interface.
What should happen. Run. Below the Roll Dice button you see "History" with a greyed-out "Clear" button, and "No rolls yet". Roll once: the message disappears and Clear becomes active (rows do not appear yet). Tap Clear: the message returns and Clear is disabled again.
Step 13 — Show the history rows
File: ContentView.swift · Where: inside the history VStack(alignment: .leading, spacing: 12), after the closing brace of if history.isEmpty { ... } and before the VStack's closing brace · Action: Add
ForEach(history) { roll in
HStack {
VStack(alignment: .leading) {
Text(roll.notation)
.font(.headline)
Text(roll.valuesDescription)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
VStack(alignment: .trailing) {
Text("\(roll.total)")
.font(.title2)
.fontWeight(.bold)
Text(roll.date.formatted(date: .omitted, time: .shortened))
.font(.caption2)
.foregroundStyle(.secondary)
}
}
Divider()
}
What it does. For each roll in history, draws a row: notation and individual values on the left, total and time on the right, followed by a divider line.
Why it is written this way.
ForEach(history)works withoutid:becauseRollResultisIdentifiable. SwiftUI tracks each row by the roll's UUID, so when a new roll is inserted at the top, it knows the existing rows simply moved down.- The closure parameter is named
roll, the same name used in theif letabove. They are different constants in different scopes; each exists only inside its own braces. - Each row reads only the model:
notation,valuesDescription,total,date. The view decides layout and fonts; the model decides content. This split will make the row easy to extract into its own view in Chapter 10. Divider()after each row separates entries without needingListstyling.
What should happen. Run (⌘R) and continue with Step 14.

Actual iOS Simulator screenshot of Checkpoint 08 after several 1D6 rolls: the latest roll in the circle and die tile, and the history rows below it, newest first. The rolled numbers on your device will differ.
This is the complete ContentView.swift at the end of this step. Compare it with your file, and fix any difference before moving on:
//
// ContentView.swift
// DiceFoundry
//
import SwiftUI
struct ContentView: View {
@State private var selectedDie: DieType = .d6
@State private var quantity: Int = 1
@State private var modifier: Int = 0
@State private var latestRoll: RollResult?
@State private var history: [RollResult] = []
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
let resultColumns = [
GridItem(.adaptive(minimum: 44))
]
var body: some View {
ScrollView {
VStack(spacing: 20) {
HStack {
Image(systemName: "dice.fill")
.font(.title)
.foregroundStyle(.orange)
Text("Dice Foundry")
.font(.largeTitle)
.fontWeight(.bold)
}
LazyVGrid(columns: columns, spacing: 12) {
ForEach(DieType.allCases) { dieType in
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(dieType == selectedDie ? .orange : .gray)
}
}
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)
if let roll = latestRoll {
Text(roll.notation)
.font(.title2)
.fontWeight(.semibold)
ZStack {
Circle()
.fill(Color.orange.opacity(0.2))
.frame(width: 140, height: 140)
Text("\(roll.total)")
.font(.system(size: 64, weight: .bold))
}
LazyVGrid(columns: resultColumns, spacing: 8) {
ForEach(roll.values.indices, id: \.self) { index in
Text("\(roll.values[index])")
.font(.title3)
.fontWeight(.semibold)
.frame(width: 44, height: 44)
.background(Color.orange.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
if roll.modifier != 0 {
Text("Dice \(roll.subtotal), modifier \(formattedModifier(roll.modifier))")
.foregroundStyle(.secondary)
}
} else {
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
.frame(height: 140)
}
Button("Roll Dice") {
performRoll()
}
.font(.title2)
.buttonStyle(.borderedProminent)
.controlSize(.large)
.tint(.orange)
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("History")
.font(.title2)
.fontWeight(.bold)
Spacer()
Button("Clear") {
history.removeAll()
}
.disabled(history.isEmpty)
}
if history.isEmpty {
Text("No rolls yet")
.foregroundStyle(.secondary)
}
ForEach(history) { roll in
HStack {
VStack(alignment: .leading) {
Text(roll.notation)
.font(.headline)
Text(roll.valuesDescription)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
VStack(alignment: .trailing) {
Text("\(roll.total)")
.font(.title2)
.fontWeight(.bold)
Text(roll.date.formatted(date: .omitted, time: .shortened))
.font(.caption2)
.foregroundStyle(.secondary)
}
}
Divider()
}
}
}
.padding()
}
}
func rollDie(sides: Int) -> Int {
let roll = Int.random(in: 1...sides)
return roll
}
func rollDice(count: Int, sides: Int) -> [Int] {
var rolls: [Int] = []
for _ in 1...count {
rolls.append(rollDie(sides: sides))
}
return rolls
}
func isValidQuantity(_ value: Int) -> Bool {
value >= 1 && value <= 10
}
func formattedModifier(_ value: Int) -> String {
switch value {
case 0:
return "0"
case 1...:
return "+\(value)"
default:
return "\(value)"
}
}
func performRoll() {
if isValidQuantity(quantity) {
let values = rollDice(count: quantity, sides: selectedDie.sides)
let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
latestRoll = roll
history.insert(roll, at: 0)
} else {
print("Invalid quantity: \(quantity)")
}
}
}
#Preview {
ContentView()
}
Step 14 — Test the history
Work through this test script:
- Launch. "Tap Roll Dice to begin" in the result area; "History", a disabled "Clear", and "No rolls yet" below.
- Roll 3D6 with modifier +2. The result shows as before. The history has one row:
3D6 + 2, the three values separated by commas, the total, and the current time. - Roll 2D20 with modifier -4. A new row appears at the top with
2D20 - 4. The first roll is now the second row. - Change the controls without rolling. Neither the result nor any history row changes.
- Roll about fifteen more times. The page grows taller than the screen; scroll down to see older rolls. The whole page scrolls as one, including the controls.
- Roll the same thing twice quickly (for example 1D4, modifier 0). Two separate rows appear even if their values and times are identical: each has its own
id. - Tap Clear. All rows disappear, "No rolls yet" returns, and Clear is disabled. The latest result stays visible in the result area.
- Stop the app (⌘.) and run it again. The history is empty. That is expected: the history lives only in memory. Chapter 9 makes it persistent.
Expected Results
After a few rolls, the screen looks approximately like this:
Illustrative mockup — not a screenshot
[dice] Dice Foundry
[ D4 ] [ D6 ] [ D8 ]
[ D10 ] [ D12 ] [ D20 ]
Number of dice: 2 [ - | + ]
Modifier: -4 [ - | + ]
2D20 - 4
.-------.
( 18 )
'-------'
[15] [7]
Dice 22, modifier -4
[ Roll Dice ]
History Clear
2D20 - 4 18
15, 7 2:07 PM
------------------------------------------
3D6 + 2 14
4, 2, 6 2:06 PM
------------------------------------------
Your values and times will differ. What must hold:
- The newest roll is always the first history row, and it matches the result area.
- Every row's total equals the sum of its listed values plus the modifier in its notation.
- Times use your simulator's region settings (12-hour or 24-hour).
- Clear is disabled whenever the history is empty.
- The whole page scrolls as one when the history is long.
- History is lost when the app is stopped and relaunched (until Chapter 9).
Reading This Like a Developer
The flow of one roll
tap "Roll Dice"
-> Button closure { performRoll() }
-> isValidQuantity(quantity) reads control state
-> rollDice(count: quantity, sides: selectedDie.sides)
-> rollDie(sides:) x quantity -> Int.random(in: 1...sides)
-> let values = [4, 2, 6] local, not state
-> let roll = RollResult(dieType: .d6,
values: [4, 2, 6],
modifier: 2) id = UUID(), date = Date()
-> latestRoll = roll state change 1
-> history.insert(roll, at: 0) state change 2
-> SwiftUI sees @State changed, re-evaluates body
-> if let roll = latestRoll -> result area reads roll.notation,
roll.total, roll.values, roll.subtotal
-> history.isEmpty is false -> Clear enabled, "No rolls yet" removed
-> ForEach(history) -> one row per RollResult, matched by id
Two things are not in this flow yet. There is no saving to disk; that is Chapter 9. And all of the logic still lives in ContentView; in Chapter 13 it moves into a view model, and the flow gains one more layer between the button and the state.
Which variables hold state
| Property | Kind | Who changes it | Describes |
|---|---|---|---|
selectedDie, quantity, modifier |
@State |
Die buttons, steppers | The next roll |
latestRoll |
@State, optional model |
performRoll() only |
The last roll, or none |
history |
@State, array of models |
performRoll() (insert), Clear button (removeAll) |
Every roll since launch, newest first |
Compare this with Chapter 7: three loose output properties became one optional model, and a whole history became possible with one more property.
Where values originate and where they are calculated
- The dice values originate in
Int.random(in:), insiderollDie(sides:). - The die, quantity and modifier originate in the controls and are captured once, by the
RollResultinitializer. idanddateoriginate in the initializer's default values.subtotal,total,notationandvaluesDescriptionare never stored; they are calculated from the stored properties every time a view reads them.- The time text originates in
date.formatted(...), at display time, using the device's locale.
Business logic versus presentation logic
RollResult now contains the core rules of the domain: what a roll consists of, how its total is calculated, and how dice notation is written. It contains no SwiftUI and has no idea what a screen is. That makes it reusable (any view can display a roll) and testable (Chapter 12 tests it without launching the interface). ContentView still contains some logic (rolling, validation, history management) alongside layout. It is getting long; Chapter 10 splits the layout into components, and Chapters 12 and 13 move the remaining logic out.
valuesDescription and notation are arguably presentation, since they produce text. They live in the model because they are part of what a roll is in this domain (dice notation is the standard way to write a roll), and because several views need them identically. formattedModifier and the date's display style stay in the view for now, because they are decisions about one particular screen.
How errors are handled
As in Chapter 7, the only failure path is an invalid quantity, handled by printing a message. The model itself cannot be created in an invalid state by accident: it has no optional or missing properties, and its initializer requires all the essential data.
When you ask an assistant to "add roll history", check four things in what it produces. (1) Does it create a model type, or does it add more parallel arrays to the view? Parallel arrays (historyValues, historyModifiers, historyDates) are a red flag; ask for "a struct representing one roll, and an array of that struct". (2) Does the model store values that can be calculated, such as total? If so, ask why; stored derived values drift. (3) Is the id stable? Code such as var id: UUID { UUID() } (a computed property) compiles but produces a new identity every time it is read, which makes SwiftUI treat every row as brand new; let id: UUID set once in the initializer is correct. (4) Is there a List inside a ScrollView? That is the nested-scrolling bug described in this chapter. Being able to name these issues lets you give an agent precise corrections instead of "it looks weird".
Troubleshooting
"Cannot find type 'RollResult' in scope"
Cannot find type 'RollResult' in scope
Meaning. The compiler does not know the type when compiling ContentView.swift.
Likely causes. The file was created without the DiceFoundry target checked; the struct name is misspelled (for example RollResults); or the struct was typed inside another type's braces.
How to investigate. Select RollResult.swift, open the File inspector (⌥⌘1), and check that DiceFoundry is ticked under Target Membership. Then check the spelling and that struct RollResult is at the top level of its file.
"Return from initializer without initializing all stored properties"
The message will be similar to:
Return from initializer without initializing all stored properties
Meaning. At least one let property was not assigned in init.
Likely causes. A missing self.date = date (or another line), usually after adding a property to the struct without updating the initializer.
How to investigate. Compare the list of stored properties with the list of self.x = x lines; there must be one assignment for each.
"Cannot assign to value: 'id' is a 'let' constant"
The message will be similar to the one in the heading, or "Cannot assign to value: ... is a 'let' constant".
Meaning. Inside the initializer you wrote id = id instead of self.id = id. Without self., both sides refer to the parameter, which is a constant.
How to investigate. Add self. on the left side of each assignment in init.
"Missing argument for parameter 'id' in call"
Meaning. A call is using the memberwise-style argument list, or your initializer has no default for id or date.
Likely causes. id: UUID without = UUID() in the init declaration (or the same for date). Before Step 2, it means you are calling the memberwise initializer without all five arguments.
"Extra argument 'id' in call" or "Incorrect argument labels in call"
Meaning. The arguments do not match the initializer. For example, after Step 2 the memberwise initializer no longer exists, so a call with id: first, as shown in the memberwise example, does not match.
How to investigate. Use code completion: type RollResult( and look at the suggested parameter list, then match it. Arguments must appear in declaration order.
"Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'RollResult' conform to 'Identifiable'"
The message will be similar to the heading.
Meaning. ForEach(history) needs to know how to identify each element.
Likely cause. : Identifiable is missing from the struct RollResult declaration.
The history is empty, or the result never appears, after Step 9
Meaning. Expected between Step 9 and Step 10: performRoll() sets latestRoll and history, but the result area still reads the old results. After Step 10 the result appears; after Step 13 the rows appear.
Rows appear at the bottom instead of the top
Likely cause. history.append(roll) instead of history.insert(roll, at: 0).
The Clear button never becomes enabled, or is always enabled
Likely causes. .disabled(!history.isEmpty) (inverted condition), or .disabled attached to the wrong view, such as the HStack, which disables everything inside it.
Nothing scrolls, or the history appears as a tiny box
Likely causes. The ScrollView wraps only part of the page, or a List was used inside the ScrollView. Check that ScrollView { is the first view in body and wraps the entire VStack, and that the history uses ForEach, not List.
The time is not in the format you expected
Meaning. Not a bug. formatted(date:time:) follows the simulator's region and language settings (Settings app → General → Language & Region in the simulator). A 24-hour region shows 14:07.
Knowledge Check
- Explain, using Dice Foundry as the example, why one completed roll should be a single
RollResultvalue rather than several separate state properties. Give at least two concrete problems the structure prevents. - What is the difference between a stored property and a computed property? Why is
totalcomputed rather than stored? - Swift generates a memberwise initializer for
RollResult. Why does the project write its own initializer, why doidanddatehave default values, and what happens to the memberwise initializer once you write your own? RollResultis a structure, a value type. AfterlatestRoll = rollandhistory.insert(roll, at: 0), how manyRollResultvalues exist, and why can neither copy be changed through the other?- Why does Dice Foundry use
ForEachinside aScrollViewfor the history instead of aList, and what usually goes wrong when aListis placed inside aScrollView?
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.
Show the number of rolls in the history heading, for example "History (5)". Below the heading, when the history is not empty, show the average total of all rolls in the history with one decimal place, for example "Average total: 11.4". Calculate the average in a computed property of ContentView. Clearing the history must reset both.
Add two computed properties to RollResult: the lowest and the highest total that roll could possibly have produced (for 3D6 + 2: 5 and 20). Show them in each history row, below the individual values, for example "Possible: 5 to 20". Do not add any stored properties.
Limit the history to the 20 most recent rolls. When a 21st roll is added, the oldest one must be removed. Use only array operations you have learned.
Requirements, acceptance criteria and progressive hints are in the Chapter 8 Exercises document. Do the challenges on a separate Git branch, as described there.
Chapter Completion Checklist
RollResult.swiftexists, belongs to the DiceFoundry target, and matches the reference.- I can explain the difference between stored and computed properties and which ones
RollResulthas. - I can write the call to a memberwise initializer and explain why the project replaces it with a custom one.
- I can explain
self.id = id. - I can explain value semantics and predict the result of copying a structure or an array of structures.
- I can explain why each roll has a
UUID, and why an index or a date would not be a good identity. - I can explain what
Identifiablerequires and what it allows inForEach. - I can read
values.map { String($0) }.joined(separator: ", ")step by step. ContentViewuseslatestRoll: RollResult?withif let, andhistory: [RollResult].- The old
results,rolledModifier,rolledNotation,subtotal,total,sum(of:)andnotation(...)are gone fromContentView. - The page scrolls as one, and I can explain why the spacers were removed and why there is no
List. - New rolls appear at the top of the history with notation, values, total and time.
- Clear empties the history and is disabled when the history is empty.
- I ran the test script in Step 14.
Development Checkpoint
In Xcode: choose Integrate → Commit… (or Source Control → Commit… in some versions). Make sure both ContentView.swift and the new RollResult.swift are included (a new file shows an "A" for added), type the message Chapter 8: RollResult model and roll history, and commit.
In Terminal, from your project folder:
git add -A
git commit -m "Chapter 8: RollResult model and roll history"
git tag chapter-08
git status
git status should report a clean working tree. If it lists RollResult.swift as untracked, the git add -A step was skipped.
To compare with the reference, open Reference-Checkpoints/Checkpoint-08-Roll-History/DiceFoundry/ and compare RollResult.swift and ContentView.swift with yours, or use diff in Terminal with your own paths:
diff /path/to/Reference-Checkpoints/Checkpoint-08-Roll-History/DiceFoundry/RollResult.swift DiceFoundry/RollResult.swift
diff /path/to/Reference-Checkpoints/Checkpoint-08-Roll-History/DiceFoundry/ContentView.swift DiceFoundry/ContentView.swift
Differences in the comment header are harmless. If you kept a practice file with #Playground blocks, it will not exist in the reference; that is fine.
Prediction Answers
Value semantics (Step 6). The playground prints:
2 1
true
2
backup = history made an independent copy of the one-element array. Inserting second into history makes history contain two rolls while backup still contains one. history[1] is a copy of first, and a copy keeps the same id, so the comparison is true: copying a value does not create a new identity, only calling the initializer does. Finally, backup.removeAll() empties only backup; history still has 2 elements.
The model at work (Step 6, first playground). penalty.notation is "2D20 - 4" and penalty.total is 18 (15 + 7 = 22, minus 4). For the worked example, roll.subtotal and roll.total print 12 14.
Newest first (Step 9). With insert(roll, at: 0), each new roll goes to the front and pushes the others down: history[0] has total 2, history[1] has 9, history[2] has 5. latestRoll?.total is 2, the same roll as history[0]. With append, the order would be the order of rolling: 5, 9, 2, and the newest roll would be last.