Dice Foundry Exercises and Challenges

Chapter 14 Exercises — Final Project: Extending Dice Foundry

This document contains the hints for the three required features in Chapter 14, and four extra practice exercises. It does not contain full solutions. The solutions and their explanations are in ch14-answers.md.

Work the required features in the order given in Chapter 14, under Suggested Implementation Order. Commit to main when the required features pass the acceptance criteria and your tests pass. Do not create a challenge branch for the required features, because the finished project is the one you compare with the reference. Use a branch only for a stretch goal, as described in Chapter 14.

Use the hints like this:

  1. Try the step on your own first, for as long as it is productive.
  2. Read Hint 1. Try again.
  3. Read Hint 2. Try again.
  4. Read Hint 3 only when you have tried the step after Hint 2 and still cannot make it work.

Each hint gets closer to the answer. None of them is the full code, and none of them is meant to be copied line for line. If you find yourself copying, stop, close the hint, and think about what the code must do.

Required Feature 1 — The D100 (percentile) die

Goal. Add a percentile die that behaves like every other die in the app.

Requirements. The die appears in the picker as D100 with a percent symbol. It rolls values from 1 to 100. It works with quantity and modifier, and its notation and history rows read correctly. VoiceOver describes it as a 100-sided die. A history file saved before the change still loads.

Acceptance criteria. The picker shows seven dice. Rolling one D100 produces notation such as 1D100, and every value is between 1 and 100. Rolling five D100 with a modifier of -3 gives notation ending in - 3 and a total equal to the subtotal minus 3. Existing saved history loads and looks as it did before.

Hint 1

The set of dice the app knows about is defined in one file, and the place that calculates each die's name and symbol is in the same file. Add the new die there first. Then build with ⌘B and read every error the compiler shows you. Do not start in the picker view; the picker is only showing what the model already provides.

Hint 2

The number of sides comes from the value stored for each case, so the new case needs exactly one new number. The name is computed from that number, so you do not need a separate name. The symbol is different: it is a lookup, and the compiler will ask you to decide what it returns for the new case. Choose an SF Symbol whose name you have checked in Apple's SF Symbols app, because a misspelled name compiles and then shows nothing.

Hint 3

Add the one case. Build. For each switch the compiler lists, add the branch for the new case, returning the value that matches the pattern of the branches above it. Then run the app and count the buttons: seven dice in three columns means three rows of three and a single button on the last row. If your picker shows a different arrangement, you have changed something you did not intend to change.

Required Feature 2 — Natural maximum and minimum indicator

Goal. Mark each individual die value that is a natural maximum or natural minimum, and tell VoiceOver which ones they are.

Requirements. A value is a natural maximum when it equals the highest face of its die. A value is a natural minimum when it equals 1. Each die value is judged on its own, so a modifier never changes the result. The marking is visible without color. The spoken description of a roll states the count of maximum and minimum dice when there is at least one.

Acceptance criteria. A D6 roll of 6 is marked as a maximum. A D100 roll of 100 is marked. A D20 roll of 20 with a modifier of +5 is marked, while the total shows 25. Rolls with no maximum or minimum values show no marking and say nothing about them in the spoken description. Every marking has a cue that is not color alone.

Hint 1

Ask yourself "compared to what?" for each check. The highest face depends on the die that produced the value, not on the total and not on the modifier. Think about which type already knows the number of sides for a roll, and put the check next to the logic you already wrote for the notation and totals. A check that answers a question about one value is easier to test than a check that reads the view.

Hint 2

Each check needs to answer "is this one value at the top or bottom of its range?" So each check takes a single value, and possibly the die's sides, and returns a Boolean. In the result view, you will call the check once for each chip, so the loop that already draws the chips is the right place to ask. For the spoken description, you need to count how many values pass each check. Filtering the values is the natural tool, and the filter pattern is in the Syntax Breakdown in Chapter 14.

Hint 3

Think of the model as the place where the rule is written, and the result view as the place where the rule is shown. In the view, decide two things for a marked chip: what it looks like, and what it says. For the look, pick a change that does not depend on color, such as a text label, a symbol or a border with a different shape, and keep your color choice on top of that. For the spoken description, build the sentence from the counts only when a count is above zero, so that a roll with no markings says nothing extra. Test your version with a roll that has no marked values, because that case is easy to forget.

Required Feature 3 — History filter

Goal. Let the user choose one die type, or all dice, and show only the matching rows of the history.

Requirements. The filter offers All dice and one choice for each die type. All dice shows every roll. A single die type shows only matching rolls, in their original order. When there are no rolls at all, the message "No rolls yet" appears. When there are rolls but none match the filter, a different message appears. The stored history is never changed by the filter, and the filter is not saved.

Acceptance criteria. Choosing D20 hides every other die. Choosing a die you have not rolled shows the "No rolls match this filter" message. Clear removes all history, including rolls hidden by the filter. The Clear button is disabled only when the full history is empty. Relaunching the app returns the filter to All dice, and the full history is still there.

Hint 1

Look at how the selected die is stored. DiePicker writes into a property on the view model through a binding, and the view reads it back. The filter should follow the same pattern, because it is another choice the user makes. Ask yourself where the list of rows should come from, and which of the two lists in the view model should stay exactly as it is.

Hint 2

The filter needs two kinds of answer: "no filter" and "this die". Which Swift type from Chapter 2 can represent a value that might be missing? Once you have chosen it, the view model needs to produce a list. The list should be computed from the full history each time it is read, not stored as a second copy, because a stored copy can fall out of step. Ask which property the list in ContentView should loop over, and which property the empty-state check should read.

Hint 3

In the view model, add a filter property that is var so a binding can write to it, and a computed property for the filtered list. The computed property has two paths: when a filter value is present, keep only the matching rolls; otherwise return the whole history. The filter closure pattern in the Syntax Breakdown is enough for the first path. In ContentView, put the Picker in the history header. Use explicit optional tags, including a typed nil tag for "All dice", as shown in the Syntax Breakdown. Modern SwiftUI can also match nonoptional die tags to an optional selection through its default optional matching; explicit optional tags remain clear and compatible with this course's iOS 17 minimum. For the two empty-state messages, check the full history first and then the filtered list. For Clear, make sure its disabled condition and its action both use the full history.

Extra Practice Exercises

These exercises are not required. Each one practices a skill the required features use. Do them after the required features, or before the stretch goals.

Exercise 1 — Predict the output

Without running the code, predict the three values printed by this program. Write each answer down before you check it in Xcode or a playground.

Example — not part of the Dice Foundry project
let totals = [4, 17, 6, 2]
let high = totals.filter { $0 >= 6 }
print(high.count)
print(totals.allSatisfy { $0 > 1 })
print(high.allSatisfy { $0 > 6 })

Then answer this question: if totals were an empty array, what would the last two lines print, and why?

Exercise 2 — Spot the bug

The function below is meant to report whether a roll has a natural maximum, meaning at least one die showed the highest face. It has a bug. Find an input that gives the wrong answer, explain why, and rewrite the check so it is correct for every input.

Example — not part of the Dice Foundry project
struct Roll {
    let sides: Int
    let values: [Int]
    let modifier: Int

    var total: Int {
        values.reduce(0, +) + modifier
    }

    func hasNaturalMaximum() -> Bool {
        total == sides
    }
}

Hint: Compare the function's question with the definition in the Concept Explanation of Chapter 14. Which property of the roll answers the question, and which one does the function use?

Exercise 3 — Count natural maxima

Write a function that takes an array of die values and the number of sides on the die, and returns how many values are natural maxima. Use the filter closure pattern and the count property you have already met. Test your function with three inputs whose answers you calculate by hand before you run it:

  1. An empty array.
  2. An array where no value is the maximum.
  3. An array where two values are the maximum for a D6, and one value is not.

Write the expected answer for each input on paper before you run the test. If the function disagrees with your hand calculation, find out which one is wrong before you change either.

Exercise 4 — Review a generated suggestion

An AI tool suggests the following change to your view model. Read it, then answer the questions below.

Example — not part of the Dice Foundry project
@Observable
final class RollViewModel {
    var history: [RollResult] = []
    var historyFilter: DieType?
    var filteredHistory: [RollResult] = []

    func roll() {
        // ... existing roll code ...
        history.insert(newRoll, at: 0)
        applyFilter()
    }

    func applyFilter() {
        if historyFilter != nil {
            filteredHistory = history.filter { $0.values.count == 1 }
        } else {
            filteredHistory = history
        }
    }
}

Questions:

  1. Name two places where filteredHistory can become out of step with history in this version. Hint: think about clearHistory(), loadHistory() and the historyFilter property itself.
  2. Rewrite the filter so that filteredHistory cannot go stale. Describe the change in words first, then write it as a computed property, using the Chapter 14 pattern.
  3. Explain why the rewrite is safer, in one sentence, in terms a colleague who does not know Swift would understand.

Hints Checklist

  • I attempted each required feature before reading any hint.
  • I read at most one hint at a time, and retried after each.
  • I did not copy any hint text as code without understanding what it does.
  • I checked my answers to the extra exercises before reading ch14-answers.md.