Dice Foundry Solutions and Answer Key

Chapter 14 Answers — Final Project: Extending Dice Foundry

This document contains the self-assessment rubric, explained solutions to the three required features, answers to the Knowledge Check, and answers to the extra exercises. The solutions show the changes in short snippets and say where they belong. They are not complete listings. Compare your work with the reference only after you have finished and tested your own version.

Verification Status

Verified: the Final Project Solution compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target).

The course's verification run, repeated after the final fixes, printed this summary line:

Final-Project-Solution (Swift 5.0): OK  errors=0 warnings=0 test cases passed=56 failed=0 (both simulators)

The same run executed the solution's test suites on an iPhone 15 simulator (iOS 17.5) and an iPhone 18 Pro simulator (iOS 27.2), with 56 test cases passed and 0 failed.

These results apply to the reference solution only. The course has not compiled or run your own extended version, so the checks in Chapter 14 are your responsibility.

Self-Assessment Rubric

Score each area from 1 to 3: 3 for Strong, 2 for Developing, 1 for Not yet. The maximum total is 18.

Area What a Strong answer looks like Common sign of Developing or Not yet
Layer placement The maximum and minimum checks are in RollResult. The view decides only colors and wording. The filter state is in RollViewModel. Maximum logic copied into ResultView, or rolls calculated in a view.
Enum change Every switch over DieType was updated because the compiler listed it. No default was added to hide a missing case. A default: branch added only to silence an error.
Filter state The filter is a view model property, the list is computed from history, and history is never filtered in place. A second stored array that is refreshed by hand.
Accessibility The marking is visible without relying on color, and the spoken description reports counts. Only a color change, or no spoken counts.
Testing Tests cover the D100 range, the checks, and the filter. At least one expectation was calculated by hand, and the manual script was run. Tests that copy the code's output, or no tests at all.
Explanation You can state the file, the location and the reason for each change, and you can say what you did not test. Explanations that repeat "it works" without saying why.

Interpreting the total:

  • 16 to 18. You have met the course's goals for this project. Move on to a stretch goal or to your own app.
  • 12 to 15. The features work, but one area needs attention. Re-read the area in Chapter 14 and fix the gap before you move on.
  • Below 12. Start again from the acceptance criteria. Check each item in the manual test script, and fix the failing items one at a time.

Required Feature 1 — The D100 Die

File and location. Models/DieType.swift.

Change. Add one case to the enumeration, after the last existing case:

Example — not part of the Dice Foundry project
case d100 = 100

Then add a branch for the new case to the switch in the symbol property, returning a symbol whose name you checked in Apple's SF Symbols app:

Example — not part of the Dice Foundry project
case .d100:
    return "percent"

Why it works. sides is rawValue, so the number 100 gives the die 100 sides, and the existing name property produces "D100" without any change. DieButton, DiePicker and the history rows all loop over DieType.allCases or read sides, so they pick up the new die with no edits. accessibilityName is computed from sides, so VoiceOver reads "100-sided die" automatically.

Why the compiler finds the switch. Once you add the case, the switch in symbolName no longer covers every case. That is a compile error, and it points you to the place that needs a branch. This is the reason to prefer switches without default for enumerations you own.

Why saved history still loads. Existing cases keep their raw values, so the JSON written by earlier versions still decodes. Adding a case does not change any raw value that was saved.

Alternatives. You could choose a different symbol, such as a custom shape from the asset catalog, but that is more work and needs a separate design decision. You could also return a plain string such as "%" from another property, but then the picker would not match the symbol style of the other dice.

Expected behavior after the change. The picker has seven buttons, with the D100 button in the last row by itself. Rolling a D100 gives notation such as 1D100 and a value from 1 to 100.

Required Feature 2 — Natural Maximum and Minimum

The rule in the model

File and location. Models/RollResult.swift, after the notation and valuesDescription properties, inside the struct.

Change. Add two functions:

Example — not part of the Dice Foundry project
func isMaximum(_ value: Int) -> Bool {
    value == dieType.sides
}

func isMinimum(_ value: Int) -> Bool {
    value == 1
}

Why it works. Each function takes one die value, which is a single entry from values, and compares it with a fixed number that comes from the roll's own die type or from the rules of the game. The functions do not read total or modifier, so a modifier can never change which dice are marked. The _ before value removes the argument label, so you call roll.isMaximum(20).

Why in the model. The rule would still be true if the app had no screen. Keeping it in RollResult means you can test it directly, and any future screen that shows a roll can use it without copying the logic.

The common mistake. Comparing total with sides gives wrong answers for every roll with a modifier. A roll of 20 plus +5 has a total of 25, which is not the maximum, but the die still showed 20.

Showing the markings in the view

File and location. Views/ResultView.swift, in the loop that draws the chips, and in the function that chooses the chip color.

Change. Ask the model for each value's status and choose the chip's style from the answer. The reference solution does this with a small helper that returns a color:

Example — not part of the Dice Foundry project
private func chipColor(for value: Int, in roll: RollResult) -> Color {
    if roll.isMaximum(value) {
        return Theme.gold
    } else if roll.isMinimum(value) {
        return Color.red.opacity(0.25)
    } else {
        return Theme.backgroundSecondary
    }
}

Why it is written that way. The view asks the model a question and decides only what to show. The if chain order matters: a value is checked against the maximum first, so a die with one side (which would be both) would show the maximum. No die in the app has one side, so the order is safe here.

The non-color cue. Color alone is not enough, so the chip also carries a small SF Symbol in its top trailing corner: an up arrow for a maximum and a down arrow for a minimum. SF Symbols are the same kind of icon that Chapter 11 uses on the die buttons. A second small helper chooses the symbol, and it returns nil for an ordinary chip:

Example — not part of the Dice Foundry project
private func chipSymbol(for value: Int, in roll: RollResult) -> String? {
    if roll.isMaximum(value) {
        return "arrow.up"
    } else if roll.isMinimum(value) {
        return "arrow.down"
    } else {
        return nil
    }
}

The chip draws the symbol with if let symbol = chipSymbol(for: value, in: roll) inside an .overlay(alignment: .topTrailing), so unmarked chips draw nothing extra. The symbol is a visual cue only. VoiceOver users get the same information from the spoken description, which is why the whole result is one accessibility element.

Another limitation. Color.red.opacity(0.25) is a fixed color, not a color from the asset catalog, so it does not adapt to Dark mode the way Theme.gold and Theme.backgroundSecondary do. A stronger version adds a color set for the minimum cue, following the Chapter 11 pattern.

The spoken description

File and location. Views/ResultView.swift, in the computed property that builds the accessibility label.

Change. Count the maximum and minimum values, and append a sentence only when a count is above zero:

Example — not part of the Dice Foundry project
let maximumCount = roll.values.filter { roll.isMaximum($0) }.count
if maximumCount > 0 {
    description += " \(maximumCount) at maximum."
}

Why it works. filter returns the values that pass the test, and .count counts them. The closure { roll.isMaximum($0) } uses $0 for each value in turn, and it calls the model's rule, so the description and the chips cannot disagree.

Expected behavior. A roll with no maximum or minimum values says nothing extra. A roll with one maximum says "1 at maximum."

Required Feature 3 — History Filter

The state in the view model

File and location. ViewModels/RollViewModel.swift, with the other choices the user makes, after modifier.

Change. Add a filter that is optional and writable, and a computed list:

Example — not part of the Dice Foundry project
var historyFilter: DieType?

var filteredHistory: [RollResult] {
    if let historyFilter {
        return history.filter { $0.dieType == historyFilter }
    } else {
        return history
    }
}

Why it works. historyFilter is nil when the user has chosen All dice. When it holds a die type, the computed property returns only the matching rolls. filteredHistory has no storage of its own, so it is calculated from history each time it is read. The view therefore always sees the current history, even after a roll, a clear or a relaunch.

Why it is not private(set). The private(set) modifier in Chapter 13 means outside code can read the property but not write it. The Picker must write the chosen die into the filter through a binding, so the filter must be writable from the view. The rule for the view model's results (latestRoll, history) still holds, because the history itself stays private(set).

Why the history is untouched. Nothing in this code removes a roll. history continues to hold every roll, and saveHistory() still saves all of them.

The Picker and the empty states

File and location. ContentView.swift, in the history section's header row, next to the Clear button. Then the lines that show the empty-state messages and the list.

Change. Add a Picker bound to the filter. Its selection type is DieType?. Use explicit optional tags for clarity and compatibility with the course's iOS 17 minimum:

Example — not part of the Dice Foundry project
Picker("Filter", selection: $viewModel.historyFilter) {
    Text("All dice").tag(DieType?.none)
    ForEach(DieType.allCases) { dieType in
        Text(dieType.name).tag(DieType?.some(dieType))
    }
}
.pickerStyle(.menu)

Why each tag is written that way. DieType?.none is the optional form of nil, which means "no filter". DieType?.some(dieType) wraps each die in an optional, so its type matches the selection. Modern SwiftUI also allows .tag(dieType) to match an optional selection because tag(_:includeOptional:) enables optional matching by default. The explicit optional form shown here is a deliberate compatibility and readability choice, not a universal requirement. The "All dice" row still needs a tag selecting nil.

For the empty-state messages, check the full history first, then the filtered list:

Example — not part of the Dice Foundry project
if viewModel.history.isEmpty {
    Text("No rolls yet")
} else if viewModel.filteredHistory.isEmpty {
    Text("No rolls match this filter")
}

The list then loops over viewModel.filteredHistory instead of viewModel.history.

Why the order of the checks matters. If you checked the filtered list first, a filter that matches nothing would show "No rolls yet" even when rolls exist, which is misleading.

Clear

File and location. ContentView.swift, the Clear button, and RollViewModel.clearHistory().

Behavior in the reference. The button is disabled when viewModel.history.isEmpty is true, and its action calls clearHistory(), which removes everything from history. The filter is not changed. This matches the acceptance criteria: the button depends on the full history, and it clears everything, including rows the filter hides.

Why it matters. If the button read filteredHistory, it would become disabled whenever a filter matched nothing, even though rolls still existed and could be cleared.

Answers to the Knowledge Check

  1. The rule is a fact about a roll, so it belongs in RollResult, the model, and not in the view. A test can call isMaximum(20) on a D20 roll without starting the app, and assert that the answer is true. A second test can assert that isMaximum(19) is false.

  2. A second stored array can fall out of step when a roll is added, the history is cleared or loaded, or the filter changes, and the code forgets to refresh the copy. The user then sees rows that do not match the saved history. A computed property has no stored copy, so it is calculated from history and the filter each time it is read, and it cannot be stale.

  3. The compiler knows every switch over the enumeration, and it reports each one that lacks the new case. Your memory cannot be as complete. You still need to read the code yourself to check behavior the compiler cannot see, such as the picker layout, the spoken description, and whether a default branch quietly returns the wrong value.

  4. "All dice" must select nil, meaning no filter. .tag(DieType?.none) supplies that value with an explicit type. Modern SwiftUI can also match a nonoptional die tag to the optional selection through tag(_:includeOptional:), which enables optional matching by default. A die value selects that die; it does not select nil.

  5. The natural maximum is a fact about the die value, not about the total. The check is roll.isMaximum(20), which compares the die value with the die type's sides. The modifier is stored separately in modifier and is not part of values, so it does not affect the check. A roll of 20 with +5 has a total of 25, but its values still contain 20.

Answers to the Extra Practice Exercises

Exercise 1 — Predict the output

Starting values: totals is [4, 17, 6, 2].

  1. high keeps the values that are 6 or more: 17 and 6. high.count prints 2.
  2. totals.allSatisfy { $0 > 1 }: every value (4, 17, 6, 2) is greater than 1, so it prints true.
  3. high.allSatisfy { $0 > 6 }: 17 passes, but 6 does not, so it prints false.

For an empty array, allSatisfy returns true, because no item fails the test. The second line would print true even though there is nothing to check. Keep this in mind when you use allSatisfy to validate data. If an empty list should be an error, check isEmpty separately.

Exercise 2 — Spot the bug

The bug is in hasNaturalMaximum(). It compares the total, which is the dice sum plus the modifier, with the number of sides. The question is whether any die showed the highest face, so the function must look at the individual values.

Two inputs show the problem:

  • sides 6, values [3, 2], modifier 1. The total is 6, so the function returns true. No die showed a 6.
  • sides 6, values [6], modifier 2. The total is 8, so the function returns false. A die did show a 6.

A correct version checks the values:

Example — not part of the Dice Foundry project
func hasNaturalMaximum() -> Bool {
    values.contains { $0 == sides }
}

contains returns true when at least one item passes the test, which is the question the function asks. The $0 refers to each value in turn, as in the filter examples.

Exercise 3 — Count natural maxima

One correct version is:

Example — not part of the Dice Foundry project
func countNaturalMaxima(_ values: [Int], sides: Int) -> Int {
    values.filter { $0 == sides }.count
}

The three hand-calculated tests are:

  1. An empty array returns 0, because there are no values.
  2. [1, 2, 3] with sides 6 returns 0, because no value is 6.
  3. [6, 6, 3] with sides 6 returns 2, because two values are 6.

If a test fails, check your hand calculation first, then check the function. Changing the function to make a test pass, without checking your expectation, is the mistake the Chapter 14 testing warning describes.

Exercise 4 — Review a generated suggestion

  1. The copy in filteredHistory can go stale in several places. Two examples: clearHistory() changes history but does not call applyFilter(), so the copy still shows the cleared rows. loadHistory() replaces history but may not refresh the copy either. Changing historyFilter by itself does not call applyFilter(), so the list does not update until another action runs it.

  2. Describe the change first: delete the stored filteredHistory array and the applyFilter() function, and make filteredHistory a computed property that reads history and historyFilter each time it is used. The rewrite is:

Example — not part of the Dice Foundry project
var filteredHistory: [RollResult] {
    if historyFilter != nil {
        return history.filter { $0.dieType == historyFilter }
    } else {
        return history
    }
}

In the exercise, the filter condition was a placeholder, so you may keep your own condition. The important changes are the removal of the stored copy and the removal of every call to applyFilter().

  1. In plain words: the list is worked out from the source each time it is shown, so it cannot disagree with the source.

Answers for Stretch Goals

No solutions are given for the stretch goals. Each one depends on design decisions you should make and test yourself. Note these points as you plan:

  • Favorites. Decide whether a favorite is part of the saved data. If it is, a new property on RollResult changes the file format, so test that a file written before the change still loads.
  • Statistics. Decide whether the statistics use the full history or the filtered list, and say why in your code comments or your notes.
  • Sound preference. The preference is a small change, following the hapticsEnabled pattern. Playing a sound needs a framework, so check the documentation for the iOS 17.0 minimum before you add one.
  • History limit. HistoryStore.maximumCount is a constant. Turning it into a preference means the trimming logic and the tests must read the same value, and a smaller limit must trim the saved history at the moment the limit changes.

Notes on the Reference Solution

The reference solution implements the required features as written. It has three limitations you should know about:

  1. The arrow symbols are small, and they show only direction. A user may have to learn that an up arrow means maximum. A text label such as "Max" would be clearer but needs more room on a 44-point chip.
  2. The minimum chip color is a fixed red, not an asset-catalog color, so it does not adapt to Dark mode.
  3. The test named for decoding an older history file (oldHistoryStillDecodesAfterAddingD100) decodes a hard-coded JSON string in the format the app wrote before D100 existed. The string is written by hand to match the encoder's output for RollResult, and it covers only D6 and D20 records, so it does not prove the same for every die.

These are good review exercises. If you find another limitation, check it against the acceptance criteria, and decide whether it matters for your version.