Dice Foundry Solutions and Answer Key

Chapter 8 Answers — Structures and Data Models

Knowledge Check Answers

1. Why one RollResult value instead of several state properties?

A completed roll is one fact with several parts: die, values, modifier, time. As separate properties (results, rolledModifier, rolledNotation), nothing in the code ties them together. Problems the structure prevents: (a) forgetting to update one of them, so they disagree; (b) needing parallel arrays to keep a history, where index 7 in one array must always match index 7 in the others; (c) duplicated logic, such as the notation calculated in the view from separate inputs; (d) meaningless placeholder values before the first roll, which an optional RollResult? replaces with a clean nil. With the model, the history is simply [RollResult], and passing, storing or (in Chapter 9) saving a roll moves all of its parts together.

2. Stored versus computed properties; why is total computed?

A stored property holds a value inside every instance (values, modifier, date). A computed property has no storage; it calculates its value from other properties each time it is read (subtotal, total, notation, valuesDescription). total is computed because it is fully determined by values and modifier. Storing it would create a second copy of the same fact that could disagree with the first; computing it guarantees it is always correct, and the calculation is trivially cheap.

3. Why a custom initializer, why defaults, and what happens to the memberwise initializer?

The memberwise initializer requires every stored property, so every caller would have to write id: UUID() and date: Date(), decisions the caller should not be making and an opportunity for mistakes such as reusing an id. The custom initializer requires only the die, values and modifier; id and date default to a new UUID and the current time, evaluated freshly on every call. They remain parameters so that tests and loading code can supply exact values. Once you write any initializer inside the structure's declaration, Swift stops generating the memberwise initializer, so the custom one becomes the only way to create a RollResult.

4. How many values exist after latestRoll = roll and history.insert(roll, at: 0)?

Three, conceptually: the local constant roll, the copy stored in latestRoll, and the copy stored in the history array. (When performRoll() returns, the local constant disappears, leaving two.) Structures are value types, so each assignment copies the value. All of a RollResult's properties are let, so no copy can be changed at all; and even if they were var, changing one copy would not affect the others. (Swift optimizes copies behind the scenes, but the behavior is always as if each is independent.)

5. Why ForEach in a ScrollView instead of a List?

The whole screen (controls, result, button and history) should scroll as one page. That calls for one ScrollView around the page, with the history rows produced by ForEach. A List is itself a scrolling container; placed inside a ScrollView scrolling the same direction, it receives conflicting layout information and typically collapses to a tiny or zero height, or becomes a small box that scrolls separately from the page. A List is the right choice when the list is the entire screen. For a history capped at 50 rolls (Chapter 9), creating every row eagerly in a VStack is not a performance concern.

Challenge Solutions

Challenge 1 — History statistics

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Reference solution folder: challenge-solutions/ch08-history-stats/.

File: ContentView.swift. Where: inside struct ContentView, after let resultColumns = [...] and before var body: some View. Action: Add.

Example — not part of the Dice Foundry project
    var averageTotal: Double {
        if history.isEmpty {
            return 0
        }
        let sum = history.map { $0.total }.reduce(0, +)
        return Double(sum) / Double(history.count)
    }

Where: the history heading Text("History"). Action: Replace with:

Example — not part of the Dice Foundry project
                        Text("History (\(history.count))")

Where: the if history.isEmpty { ... } block in the history section. Action: Replace with:

Example — not part of the Dice Foundry project
                    if history.isEmpty {
                        Text("No rolls yet")
                            .foregroundStyle(.secondary)
                    } else {
                        Text("Average total: \(averageTotal.formatted(.number.precision(.fractionLength(1))))")
                            .foregroundStyle(.secondary)
                    }

Why it works. history.map { $0.total } turns [RollResult] into [Int], and reduce(0, +) adds them up, the same pattern subtotal uses on dice values. Converting to Double before dividing keeps the fraction (integer division would turn 23 / 2 into 11). The early return 0 prevents dividing by zero; with Double, 0 / 0 would produce "not a number" (NaN) rather than crash, and it would be displayed as something like "NaN". The view only shows the average when the history is not empty, so the 0 is never displayed. formatted(.number.precision(.fractionLength(1))) always produces exactly one decimal digit, using the device's decimal separator. Because both texts read history, SwiftUI updates them on every roll and on Clear without extra code.

Alternatives. A for roll in history { sum += roll.total } loop is equally correct. String(format: "%.1f", averageTotal) is common in older and AI-generated code; it works but ignores the user's locale (always a period). Putting averageTotal in RollResult would be wrong: it describes the history, not a single roll. In Chapter 13 a property like this would naturally live in the view model.

Challenge 2 — Possible range

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Reference solution folder: challenge-solutions/ch08-possible-range/.

File: RollResult.swift. Where: inside struct RollResult, before var valuesDescription. Action: Add.

Example — not part of the Dice Foundry project
    var lowestPossible: Int {
        values.count + modifier
    }

    var highestPossible: Int {
        values.count * dieType.sides + modifier
    }

File: ContentView.swift. Where: inside the ForEach(history) row, in the leading VStack(alignment: .leading), after the Text(roll.valuesDescription) and its two modifiers. Action: Add.

Example — not part of the Dice Foundry project
                                Text("Possible: \(roll.lowestPossible) to \(roll.highestPossible)")
                                    .font(.caption2)
                                    .foregroundStyle(.secondary)

Why it works. Every die shows at least 1, so the minimum dice sum is the number of dice, values.count; the maximum is values.count * dieType.sides. Both get the roll's own modifier. For 3D6 + 2: 3 + 2 = 5 and 18 + 2 = 20. For 2D20 - 4: 2 - 4 = -2 and 40 - 4 = 36. They are computed, so they cannot disagree with the stored data, and they live in the model because they describe a roll, so any view can use them.

Alternatives. Using a range type (var possibleRange: ClosedRange<Int> { lowest...highest }) is elegant, and lets you write roll.possibleRange.contains(roll.total) in a test. Using quantity or selectedDie from the view would be wrong: they describe the next roll.

Challenge 3 (stretch) — Keep the last 20 rolls

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Reference solution folder: challenge-solutions/ch08-history-limit/.

File: ContentView.swift. Where: inside performRoll(), directly after history.insert(roll, at: 0). Action: Add.

Example — not part of the Dice Foundry project
            if history.count > 20 {
                history.remove(at: history.count - 1)
            }

Why it works. New rolls go to index 0, so the oldest is always at the last index, history.count - 1. Because exactly one roll is added at a time, removing at most one keeps the count at or below 20. Checking after the insert means the history briefly holds 21 elements inside the function, but SwiftUI only redraws after the function finishes, so the user never sees 21.

Alternatives. history.removeLast() does the same thing and is what Chapter 9 uses, together with a named constant (maximumCount) instead of the literal 20. A while history.count > 20 loop would also handle the case where many items arrive at once. Removing the oldest before inserting (if history.count == 20) works too but is easier to get wrong.

Practice Exercise Answers

A — Predict the output

2D10 - 5
7
3, 9
false
true
true

The total is 3 + 9 - 5 = 7. a and b were created by two separate initializer calls, so each received its own UUID(): different identities, identical contents. c is a copy of a, and copying preserves the id. [Int] arrays can be compared with ==, which compares contents.

B — Spot the bug

  1. var id: UUID { UUID() } is a computed property that creates a new UUID every time it is read. The type compiles and conforms to Identifiable, but its identity is never stable: ForEach sees every row as a brand-new item on every render, which breaks animations and row tracking and wastes work. Identity must be stored once: let id: UUID, assigned in the initializer.
  2. Without self., both sides of id = id refer to the parameter, which is a constant. The compiler reports errors similar to "Cannot assign to value: 'id' is a 'let' constant" for each line, and the stored properties are never initialized. Write self.id = id and so on.
  3. total is stored alongside values and modifier, and modifier and total are var. Changing modifier (or creating the value with an inconsistent total) leaves total wrong. Make every property let and compute total.

C — Formatting variations

Output varies with the simulator's locale. Typical examples in a US English region: .omitted/.shortened gives "2:05 PM"; .numeric/.omitted gives "12/5/2026"; .abbreviated/.shortened gives "Dec 5, 2026, 2:05 PM"; .long/.standard gives "December 5, 2026 at 2:05:31 PM". Changing the separator to " + " produces "4 + 2 + 6", which reads like an equation and pairs well with the total. However, if more than one screen displays values, changing the model changes them all; when a format is specific to one screen, it belongs in that view, while a format that is part of the domain (like dice notation) belongs in the model.

D — Memberwise initializer

Before adding an initializer, DiceSet(name: "Attack", dieType: .d20, count: 1) works, using the generated memberwise initializer with labels in declaration order. After adding a custom init(name: String, dieType: DieType, count: Int = 1) inside the struct, calls that pass all three arguments still compile because the custom initializer accepts them, and a new call DiceSet(name: "Damage", dieType: .d6) also works. If your custom initializer had a different parameter list (say, no count parameter), the earlier calls would fail with an error similar to "Extra argument 'count' in call", because writing any initializer in the struct's body removes the memberwise one.