Dice Foundry Exercises and Challenges

Chapter 8 Exercises — Structures and Data Models

These exercises build on the Chapter 8 project. Do them on a separate Git branch so your guided project stays identical to the reference checkpoint:

First commit and tag the guided work using the workbook's Development Checkpoint. Confirm git status --short prints nothing, then create the branch:

git switch -c challenge-08

When you are finished (whether or not you solved everything), commit your challenge edits (including unfinished work), then return to the main line before starting Chapter 9:

Uncommitted edits can follow you across branches. Save them before switching; if nothing changed, skip add and commit. The status command should print nothing:

git add -A
git commit -m "Challenge 08: Save practice work"
git status --short
git switch main

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

Challenge 1 — History statistics

Goal: work with an array of custom structures: count it, transform it with map, and summarize it.

Requirements:

  • Change only ContentView.swift.
  • The history heading shows the number of rolls, for example "History (5)".
  • When the history is not empty, a line below the heading shows the average total of all rolls in the history, with exactly one decimal place, for example "Average total: 11.4". When the history is empty, the existing "No rolls yet" message shows instead.
  • The average is calculated in a computed property of ContentView that returns a Double.

Acceptance criteria:

  • The project builds with no errors or warnings.
  • At launch the heading reads "History (0)" and "No rolls yet" is shown.
  • After rolls with totals 14 and 9, the heading reads "History (2)" and the average reads "Average total: 11.5".
  • Tapping Clear returns to "History (0)" and "No rolls yet".
  • The app never crashes or shows "NaN", including when the history is empty.

Hint 1

The count is easy: interpolate history.count into the heading text. For the average, you need two numbers: the sum of every roll's total, and how many rolls there are. You already know a method that turns an array of one thing into an array of another thing, and a method that adds up an array of Int.

Hint 2

history.map { $0.total } gives you an [Int] of totals. Add them with reduce(0, +). To divide and get a fractional result, convert both numbers to Double first, as you did in Chapter 2. Think about what dividing by zero would mean, and handle the empty case with an if that returns 0 early.

Hint 3

To show one decimal place, ask the Double to format itself: averageTotal.formatted(.number.precision(.fractionLength(1))). Put the average Text in an else branch attached to the existing if history.isEmpty { ... }.

Challenge 2 — Possible range

Goal: add computed properties to your own model and display them.

Requirements:

  • Add two computed properties to RollResult: the lowest total and the highest total the roll could possibly have produced, given its number of dice, die type and modifier.
  • Do not add stored properties, and do not change the initializer.
  • In each history row, below the individual values, show "Possible: lowest to highest".

Acceptance criteria:

  • The project builds with no errors or warnings.
  • A 3D6 + 2 row shows "Possible: 5 to 20".
  • A 2D20 - 4 row shows "Possible: -2 to 36".
  • A 1D8 row shows "Possible: 1 to 8".
  • Every row's actual total lies within its possible range.

Hint 1

Each die shows at least 1 and at most its number of sides. Which stored properties tell you how many dice were rolled and how many sides each has?

Hint 2

The lowest total is "every die shows 1, plus the modifier". The highest is "every die shows its maximum, plus the modifier". The number of dice is values.count, the sides are dieType.sides.

Hint 3

Write them like subtotal: var lowestPossible: Int { ... } with a one-line body. One body multiplies; one does not. Add a third Text to the leading VStack of the history row with .font(.caption2) and .foregroundStyle(.secondary).

Challenge 3 (stretch) — Keep the last 20 rolls

Goal: enforce a numeric bound on a collection.

Requirements:

  • Change only performRoll() in ContentView.swift.
  • The history never holds more than 20 rolls. When a new roll would make it 21, the oldest roll is removed.
  • Use only array operations from Chapters 6 and 8.

Acceptance criteria:

  • The project builds with no errors or warnings.
  • After 25 rolls, the history has exactly 20 rows (scroll and count, or temporarily show history.count as in Challenge 1).
  • The newest roll is at the top; the five oldest rolls are gone.

Hint 1

Where in the array is the oldest roll, given that new rolls are inserted at index 0?

Hint 2

After inserting, check the count with an if. The oldest roll is at the last index, which is history.count - 1.

Hint 3

Chapter 6 introduced remove(at:). Call it with the last index inside if history.count > 20 { ... }. (Chapter 9 shows a shorter way to remove the last element and uses a named constant for the limit.)

Practice Exercise A — Predict the output

What does this print? Decide before you run it in a playground.

Example — not part of the Dice Foundry project
let a = RollResult(dieType: .d10, values: [3, 9], modifier: -5)
let b = RollResult(dieType: .d10, values: [3, 9], modifier: -5)
let c = a
print(a.notation)
print(a.total)
print(a.valuesDescription)
print(a.id == b.id)
print(a.id == c.id)
print(a.values == b.values)

Practice Exercise B — Spot the bug

Each snippet compiles (or almost). Find the problem and explain its effect.

  1. A model whose identity is computed:
Broken code — for diagnosis practice
struct RollResult: Identifiable {
    var id: UUID { UUID() }
    let dieType: DieType
    let values: [Int]
    let modifier: Int
}
  1. An initializer without self.:
Broken code — for diagnosis practice
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
    id = id
    dieType = dieType
    values = values
    modifier = modifier
    date = date
}
  1. A model that stores its total:
Broken code — for diagnosis practice
struct RollResult {
    let values: [Int]
    var modifier: Int
    var total: Int
}

Practice Exercise C — Formatting variations

In a playground, create one RollResult and print its date using at least four different combinations of date: (.omitted, .numeric, .abbreviated, .long, .complete) and time: (.omitted, .shortened, .standard, .complete). Then change valuesDescription (on your challenge branch) to separate values with " + " so that a row reads "4 + 2 + 6". Which separator reads better in the history? Why might you leave the model unchanged and do this formatting in the view instead?

Practice Exercise D — Memberwise initializer

Create a new structure in a playground, struct DiceSet { let name: String; let dieType: DieType; let count: Int }, without writing an initializer. Create two instances using the memberwise initializer. Then add a custom init with a default count of 1 and observe what happens to your earlier calls that passed all three arguments.