Dice Foundry Student Workbook

Chapter 14 — Final Project: Extending Dice Foundry

Every chapter so far has told you exactly what to type. This one does not. You have a working app with a tested calculation layer, a view model, reusable components, persistence and accessibility support. In this final project you add three features on your own: a percentile die, a natural maximum and minimum indicator on results, and a filter that narrows the roll history. The requirements tell you what the app must do and how you will know it is done. They do not walk you through the code. Each feature ends with the reference code, for use only when you are stuck. You decide where each change belongs, you write it, and you use the compiler, the simulator and the tests to find out whether you were right.

That is the skill this course has been building. An experienced engineer who is new to a language does not wait for a tutorial to extend a working system. They read the code that exists, decide which layer owns each change, make the smallest correct edit, and verify the result. If you can do that for Dice Foundry, you can do it for the next app, and for the AI-generated code you will read and direct from now on.

Hints are available, in a separate document, for each required feature. Use them in order. The first hint is a nudge; the last one is close to the answer. Try each requirement with no hints first, and read the hints only when you are stuck on the same problem for more than a few minutes.

Learning Objectives

By the end of this chapter you will be able to:

  • Plan a change across the model, view model and view layers before you edit any file, and state which layer owns each rule.
  • Add a case to an enum and use the compiler's exhaustiveness errors to find every switch that must be updated.
  • Write a computed or parameterized property on a model that answers a question about its own data.
  • Turn an optional value into a filter with a nil meaning "show everything" and bind it to a Picker.
  • Explain the syntax of filter, the $0 shorthand, allSatisfy and optional tag values, and use them correctly in your own code.
  • Make an interface feature accessible without relying on color alone.
  • Test a feature with the simulator, with a manual script and with unit tests, and report what you did and did not check.
  • Compare your finished project with the reference solution and explain every meaningful difference.

Concept Explanation

Plan before you type

The worst way to add a feature to an existing app is to open the file that is on screen and start typing. The better way is to answer four questions first:

  1. Which data changes? A new die type changes the set of values the app understands. A filter adds a new piece of state. The maximum and minimum indicator adds no new stored data at all; it is a question you ask of data that already exists.
  2. Which layer owns the rule? Dice Foundry is organized in layers. The model (Models/) describes what a die and a roll are. The logic layer (Logic/) produces random numbers. The view model (ViewModels/) holds the app's state and the actions that change it. The views (Views/ and ContentView.swift) only describe what appears on screen. A rule that is true no matter what the screen looks like belongs in the model. A decision about color, layout or wording belongs in a view.
  3. What must stay the same? Saved history must still load. The roll calculation must still produce the same totals. The Chapter 13 architecture must still hold: views read state from the view model and do not calculate rolls themselves.
  4. How will you know it works? Write down the observable behavior before you start. "When I roll a 20 on a D20, the chip is marked as a natural maximum" is a test you can run. "The UI looks better" is not.

The requirements in the next section were written in this form. Use them as your plan.

Note: The plan is not the code

A plan says what a change must do and where it lives. It does not say how many lines it takes or what the code looks like. Two engineers can write different code that both meet the same acceptance criteria. The reference solution is one correct answer, not the only one.

The data path through the app

A feature in this app usually touches more than one file. The diagram below shows the three features you are about to add, and the layer each one touches. Read it from left to right: the model holds the data, the view model holds the state, and the views display it.

Models/DieType.swift       Models/RollResult.swift         ViewModels/RollViewModel.swift
  new case for D100         new properties for max/min      new filter state and a
  and its symbol                                             filtered list of history
        |                           |                                   |
        +---------------------------+-----------------------------------+
                                    |
                 Views/ResultView.swift        ContentView.swift
                   chip highlighting             Picker that writes the filter
                   spoken description            and the empty-state messages

Notice what is not in the diagram: HistoryStore, the file that saves history to disk. You will not need to change it. The filter is a way of looking at the history the app already has, so it does not change what is saved. Keeping that boundary clear is one of the main lessons of this chapter.

Feature 1: a percentile die

A percentile die, written D100 in roleplaying games, has 100 sides and is usually rolled as "percent". In Dice Foundry, every die type is a case of the DieType enumeration, and its rawValue is its number of sides. You already know that a new die type is "a new case plus any switch that must know about it". The Chapter 5, 9 and 11 code is your guide: DieType has a name and an accessibilityName computed from rawValue or sides, and a symbolName computed from a switch over self.

The compiler does a lot of this work for you. A switch over an enum must handle every case, or it must include a default branch. Whichever you choose, you should decide deliberately. A default branch that quietly returns the wrong value is the most common way a new feature breaks without warning, so the course's advice is to prefer an exhaustive switch for an enum you own.

Three things to think about for this feature:

  • Does the die need a new symbol? A die with a hundred faces does not have an SF Symbol with a hundred sides. Pick a symbol that communicates "percent" to the user, and check the name in Apple's SF Symbols app, not from memory. A wrong symbol name does not fail to compile. It shows an empty image.
  • Does the layout still work? The die picker is a grid with three columns. Adding a seventh die changes how the grid wraps. Predict the layout before you run the app; you can check your prediction in the preview.
  • Does saved history still load? Adding a case does not change the raw values of existing cases, so a history file written by Chapter 9 still decodes. Changing an existing raw value would break saved data. Keep that in mind for any change to an enum that is saved to disk.

Feature 2: natural maximum and minimum

In tabletop games, a natural result is the number the die shows before any modifier is added. A natural maximum is the highest face of the die: 20 on a D20, 100 on a D100. A natural minimum is 1 on any die. Players care about these results, so the app should mark them.

Two details matter here.

First, the indicator applies to individual die values, not to totals. A roll of 20 plus a modifier of +5 has a total of 25, but the die still showed a natural 20. The indicator must look at the values in values, and it must ignore the modifier. A common mistake is to compare total to the maximum, which gives the wrong answer for any roll with a modifier.

Second, the indicator must not depend on color alone. People who cannot see color differences, and people using VoiceOver, must still know which dice hit the maximum or minimum. Chapter 11 introduced accessibility labels for exactly this reason. You can choose the cue yourself, such as a short text label, a symbol or a shape change on the chip, plus the spoken description of the result. Whatever you choose, it must work without color.

Where should the rule live? "Is this value the maximum face of its die?" is a fact about a roll, independent of how the app looks. That makes it business logic, and it belongs in the model, next to the RollResult properties you already use for total and notation. Where should the appearance live? The color of a chip and the wording of a spoken description are presentation decisions, and they belong in ResultView.

This split is the most important architectural decision in the feature. If the rule is written inside the view, you cannot test it without running the user interface, and any future screen that shows a roll will have to repeat it.

Feature 3: the history filter

The history list currently shows every roll. The new feature lets the user choose one die type, or "All dice", and shows only the matching rolls.

The design question is where the filter's state should live. The filter is a choice the user makes, and the rest of the app's choices (the selected die, the quantity and the modifier) live in RollViewModel. Follow the same pattern. The view model holds the filter, and the view writes to it through a binding, exactly as DiePicker writes selectedDie.

The filter needs a value that means "no filter". Chapter 2 introduced optionals: a variable of type Something? can hold either a value or nil. An optional filter is a natural fit. nil means "show every die type", and any other value means "show only this die type". You do not need a separate Boolean to say whether a filter is active.

Three rules keep the filter honest:

  1. The filter never changes the history. Rolls that are hidden by the filter are still in history, still saved to disk, and still counted for the Clear button. The filter only changes which rolls the list displays.
  2. The filter is computed from the history. Rather than storing a second, filtered copy of the list, compute the filtered list on demand from the history and the current filter. Then the two can never disagree.
  3. The filter is not saved. Closing and reopening the app shows all dice again. Saving the filter would be a reasonable extension, but it is a decision you would make deliberately, with its own tests.
Predict Before You Run: What does Clear remove?

The filter is set to D6, and the history holds three D6 rolls and two D20 rolls. You tap Clear. Predict how many rows remain in history, and whether the Clear button is enabled afterward. Check your answer under Prediction Answers.

AI-Assisted Development: Reviewing AI-written feature code

AI-generated code often adds a second copy of a list for each filtered view, such as a filteredRolls array stored next to history. Copies drift out of step: a roll is added to one and not the other, and the screen shows stale data. When you review generated code, ask two questions: "Is this value stored, or computed from something else?" and "If the source changes, what updates this?" A computed property answers both questions for you.

Syntax Breakdown

This section covers the syntax you will most likely need for the required features, in a generic form. The examples use numbers, strings and made-up types, not Dice Foundry code, so you have to work out how they apply to your own changes. Syntax you have already met, such as if let, switch, enum and ForEach, is not repeated.

Exhaustive switch over an enum

Example — not part of the Dice Foundry project
enum Region {
    case north
    case south
    case west
}

func label(for region: Region) -> String {
    switch region {
    case .north:
        return "N"
    case .south:
        return "S"
    case .west:
        return "W"
    }
}

If you add case east to Region and do not update label(for:), the compiler reports an error that the switch does not cover every case. That error is a feature. It tells you the exact list of places to update. The alternative, a default: branch, silences that error and hides the omission.

Token Meaning
switch region Compare region against each case in turn.
case .north: Matches when the value is .north. The leading dot is shorthand for Region.north.
return "N" Leaves the function with this value. Each case must return or fall through to a return.
(no default) Tells the compiler that these three cases are the only ones, so it can check you.

Computed Boolean properties and parameterized functions

A computed property answers a question about the value it belongs to, with no parameters:

Example — not part of the Dice Foundry project
struct Score {
    let points: Int

    var isPerfect: Bool {
        points == 100
    }
}

A function can answer a question about a value you pass in. Here _ before the parameter name means callers do not write a label:

Example — not part of the Dice Foundry project
func isEven(_ number: Int) -> Bool {
    number % 2 == 0
}

isEven(4)   // true
Token Meaning
func isEven Declares a function named isEven.
_ number: Int The _ means the parameter has no argument label, so you call isEven(4) rather than isEven(number: 4).
-> Bool The return type.
number % 2 == 0 A single expression, so the function returns it without a return keyword.

Choose a computed property when the answer depends only on the value itself, and a function when the answer depends on something the caller supplies. Either can be a good design. Use whichever makes the call site read most clearly.

filter with a closure and $0

filter takes a list and returns a new list containing only the items for which a test is true. The test is a closure, and it is usually written as a trailing closure, which you met in Chapter 3:

Example — not part of the Dice Foundry project
let numbers = [3, 8, 15, 4]
let large = numbers.filter { number in
    number > 5
}
// large is [8, 15]

Swift lets you shorten the closure. Instead of naming the parameter, you use the automatic name $0, which stands for the first argument the closure receives:

Example — not part of the Dice Foundry project
let large = numbers.filter { $0 > 5 }
Token Meaning
numbers.filter Call filter on the array. The result is a new array; numbers does not change.
{ ... } The closure, passed as a trailing closure.
number in Names the closure's parameter. Optional when you use $0.
number > 5 The test. Each item for which this is true is kept.
$0 The automatic name for the first parameter. Swift fills it in for each item in turn.

Read { $0 > 5 } as "for each item, keep it if item is greater than 5".

Predict Before You Run: Count the kept items

Without running it, predict the value of numbers.filter { $0 > 5 }.count for let numbers = [3, 8, 15, 4]. Then predict the result of numbers.filter { $0 == 15 }.isEmpty. Check your answers under Prediction Answers.

allSatisfy

allSatisfy asks whether every item passes a test, and returns a single Boolean:

Example — not part of the Dice Foundry project
let evens = [2, 4, 6]
let allEven = evens.allSatisfy { $0.isMultiple(of: 2) }
// allEven is true

let mixed = [2, 5, 6]
let stillEven = mixed.allSatisfy { $0.isMultiple(of: 2) }
// stillEven is false
Predict Before You Run: Predict the two results

For let rolls = [4, 6, 6], predict the value of rolls.allSatisfy { $0 <= 6 }. Then predict [7, 2].allSatisfy { $0 <= 6 }. Check your answers under Prediction Answers.

allSatisfy stops at the first item that fails, and it returns true for an empty list, because no item fails. Keep the empty-list behavior in mind when you use it to validate data. The difference between filter (returns a list) and allSatisfy (returns a yes or no) is the question you are asking: "which items?" or "are all items?"

Optional values as a choice

You met optionals in Chapter 2. For a filter, the optional is a choice with three parts:

Value Meaning in the filter
nil No filter. Show everything.
A value Show only the items that match this value.

You test an optional with if let (Chapter 10) or with the nil-coalescing operator ??, which you met in Chapter 2:

Example — not part of the Dice Foundry project
var favoriteRegion: Region? = nil
let shown = favoriteRegion ?? .north

The value of shown is .north here because favoriteRegion is nil. If it held .south, shown would be .south.

Picker, selection and tags

A Picker shows a set of choices and writes the chosen one into a value through a binding. The selection: argument is the binding. Each choice is a view with a tag, and the tag is the value that is written back:

Example — not part of the Dice Foundry project
@State private var region: Region = .north

var body: some View {
    Picker("Region", selection: $region) {
        Text("North").tag(Region.north)
        Text("South").tag(Region.south)
        Text("West").tag(Region.west)
    }
}

For an optional selection, the course writes explicit optional tags. This makes the value for each row clear, including the row that selects nil:

Example — not part of the Dice Foundry project
@State private var region: Region? = nil

Picker("Region", selection: $region) {
    Text("Any region").tag(Region?.none)
    Text("North").tag(Region?.some(.north))
}
Token Meaning
Region? The selection is optional, so it can be nil.
$region A binding. The picker reads it to show the current choice and writes to it when the user chooses.
.tag(...) Attaches the value the picker writes back when this row is chosen.
Region?.none The optional type's none case: the value nil.
Region?.some(.north) The optional type's some case: wraps .north as an optional.

The rule to remember: the picker needs a matching tag for every selection value, including nil. Explicit optional tags work for this course's iOS 17 minimum. Modern SwiftUI also supports .tag(value, includeOptional: true), with includeOptional enabled by default, so a nonoptional tag can match an optional selection. A plain .tag(.north) can therefore be valid when Swift can infer Region. The explicit form above remains useful for clarity and compatibility. See Apple's tag documentation.

Tip: Why a binding, not a copy

$region is not the value of region. It is a connection to the storage that holds region. A Picker that receives a plain value could display a choice but could not change it. The same reason explains why DiePicker takes @Binding var selection, from Chapter 10, and why the view model in Chapter 13 exposes its filter as a normal var that the view can bind to.

Final Project Requirements

Warning: Teaching simplification: persistence errors are console-only

The guided app and final solution print load and save errors to Xcode's console; they do not show a failure message in the app. A failed save leaves the new history visible in memory, so the screen is not proof that it reached disk. Relaunching can restore older data. A failed load leaves history unavailable, and the next successful save can replace the unreadable file. This is enough to practice throws and catch, but it is not production-ready error handling. Before shipping, show a visible error state, offer an appropriate retry or recovery path, and preserve unreadable saved data before replacing it. Chapter 9's optional load-error-message challenge is a first step; it does not cover save failures.

Build the three features below. Each one has a short description here, and detailed acceptance criteria in the next section. You may do them in any order, but the suggested order is designed so that each step builds on the last.

Required feature 1 — The D100 (percentile) die

Add a percentile die to the app's set of dice. It must:

  • Appear in the die picker as a button labeled D100, with a symbol that represents percent.
  • Roll values from 1 to 100 inclusive.
  • Work with the quantity and modifier controls like every other die.
  • Produce notation such as 2D100 + 5 in the result and history.
  • Be spoken by VoiceOver as a 100-sided die, following the pattern of the other dice.
  • Load previously saved history without errors.
Note: Reference code

The blocks below are the reference solution's code for this feature, taken from 03-Solutions-and-Answer-Key/Final-Project-Solution/. Write the feature yourself first, then compare, or use a block when you are stuck on one file. Part of the code is shown with its surrounding file so that you can see where it belongs.

Models/DieType.swift. Add the d100 case and its symbol. The compiler's exhaustiveness error on symbolName shows you the switch that needs the new case. The name and VoiceOver text already work from rawValue, so they need no change.

Example — not part of the Dice Foundry project
//
//  DieType.swift
//  DiceFoundry
//

import Foundation

enum DieType: Int, CaseIterable, Identifiable, Codable {
    case d4 = 4
    case d6 = 6
    case d8 = 8
    case d10 = 10
    case d12 = 12
    case d20 = 20
    case d100 = 100

    var id: Int {
        rawValue
    }

    var sides: Int {
        rawValue
    }

    var name: String {
        "D\(rawValue)"
    }

    var accessibilityName: String {
        "\(sides)-sided die"
    }

    var symbolName: String {
        switch self {
        case .d4:
            return "triangle"
        case .d6:
            return "square"
        case .d8:
            return "diamond"
        case .d10:
            return "pentagon"
        case .d12:
            return "hexagon"
        case .d20:
            return "octagon"
        case .d100:
            return "percent"
        }
    }
}

Required feature 2 — Natural maximum and minimum indicator

When a roll is shown, the app must identify each die value that is the natural maximum or natural minimum for its die type. It must:

  • Treat a value as a natural maximum when it equals the highest face of its die type.
  • Treat a value as a natural minimum when it equals 1.
  • Evaluate each die value on its own, so a modifier never changes which dice are marked.
  • Show the marking on the individual chip for each die in the result, so the user can see which dice were marked.
  • Use more than color to communicate the marking.
  • Tell VoiceOver which dice are at the maximum or minimum, in the spoken description of the result.
  • Not mark anything when the roll shows no maximum or minimum values.
Note: Reference code

The blocks below are the reference solution's code for this feature, taken from 03-Solutions-and-Answer-Key/Final-Project-Solution/. Write the feature yourself first, then compare, or use a block when you are stuck on one file. Part of the code is shown with its surrounding file so that you can see where it belongs.

Models/RollResult.swift. Add the two checks next to the other computed members. They take a value as a parameter, because a RollResult holds several values.

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

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

Views/ResultView.swift. This file is shown in full, because the chip view moved inside a new ForEach body and the lines around it changed indentation. The chip styling, the non-color arrow symbol, the spoken counts and the two helper functions are all in it.

Example — not part of the Dice Foundry project
//
//  ResultView.swift
//  DiceFoundry
//

import SwiftUI

struct ResultView: View {
    let roll: RollResult?
    let rollCount: Int

    @Environment(\.accessibilityReduceMotion) private var reduceMotion
    @ScaledMetric(relativeTo: .largeTitle) private var totalSize: CGFloat = 56
    @ScaledMetric(relativeTo: .largeTitle) private var circleSize: CGFloat = 140
    @State private var rotation: Double = 0

    private let resultColumns = [
        GridItem(.adaptive(minimum: 44))
    ]

    var body: some View {
        VStack(spacing: 16) {
            if let roll {
                Text(roll.notation)
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundStyle(Theme.brass)

                ZStack {
                    Circle()
                        .fill(Theme.backgroundSecondary)
                    Circle()
                        .stroke(Theme.brassGradient, lineWidth: 4)
                    Text("\(roll.total)")
                        .font(.system(size: totalSize, weight: .bold, design: .rounded))
                        .contentTransition(.numericText(value: Double(roll.total)))
                        .animation(reduceMotion ? nil : .snappy, value: roll.total)
                }
                .frame(width: circleSize, height: circleSize)
                .rotationEffect(.degrees(rotation))

                LazyVGrid(columns: resultColumns, spacing: 8) {
                    ForEach(roll.values.indices, id: \.self) { index in
                        let value = roll.values[index]
                        Text("\(value)")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(minWidth: 44, minHeight: 44)
                            .foregroundStyle(roll.isMaximum(value) ? Theme.onBrass : Color.primary)
                            .background(chipColor(for: value, in: roll), in: RoundedRectangle(cornerRadius: 8))
                            .overlay(
                                RoundedRectangle(cornerRadius: 8)
                                    .stroke(Theme.brass.opacity(0.5), lineWidth: 1)
                            )
                            .overlay(alignment: .topTrailing) {
                                if let symbol = chipSymbol(for: value, in: roll) {
                                    Image(systemName: symbol)
                                        .font(.caption2.weight(.bold))
                                        .foregroundStyle(roll.isMaximum(value) ? Theme.onBrass : Color.primary)
                                        .padding(3)
                                }
                            }
                    }
                }

                if roll.modifier != 0 {
                    Text("Dice \(roll.subtotal), modifier \(RollResult.formatModifier(roll.modifier))")
                        .foregroundStyle(.secondary)
                }
            } else {
                VStack(spacing: 8) {
                    Image(systemName: "dice")
                        .font(.largeTitle)
                        .foregroundStyle(Theme.brass)
                    Text("Tap Roll Dice to begin")
                        .foregroundStyle(.secondary)
                }
                .frame(minHeight: circleSize)
            }
        }
        .frame(maxWidth: .infinity)
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(accessibilityDescription)
        .onChange(of: rollCount) {
            spin()
        }
    }

    private var accessibilityDescription: String {
        if let roll {
            var description = "Rolled \(roll.notation). Total \(roll.total). Dice: \(roll.valuesDescription)."
            let maximumCount = roll.values.filter { roll.isMaximum($0) }.count
            let minimumCount = roll.values.filter { roll.isMinimum($0) }.count
            if maximumCount > 0 {
                description += " \(maximumCount) at maximum."
            }
            if minimumCount > 0 {
                description += " \(minimumCount) at minimum."
            }
            return description
        } else {
            return "No roll yet. Tap Roll Dice to begin."
        }
    }

    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
        }
    }

    // A shape cue, so the marking does not depend on color alone.
    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
        }
    }

    private func spin() {
        if reduceMotion {
            return
        }
        withAnimation(.spring(duration: 0.6, bounce: 0.3)) {
            rotation += 360
        }
    }
}

#Preview("With a roll") {
    ResultView(roll: RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2), rollCount: 1)
        .padding()
}

#Preview("Empty") {
    ResultView(roll: nil, rollCount: 0)
        .padding()
}

Required feature 3 — History filter

Add a control to the history section that filters the list by die type. It must:

  • Offer "All dice" and one choice for each die type, including D100.
  • Show all rolls when "All dice" is selected.
  • Show only rolls of the selected die type when a specific die is selected.
  • Show a message when the history is empty, as the app does now.
  • Show a different message when history exists but no roll matches the filter.
  • Leave the stored history unchanged, so that choosing "All dice" again shows every roll.
  • Keep the Clear button working as described in the acceptance criteria.
Note: Reference code

The blocks below are the reference solution's code for this feature, taken from 03-Solutions-and-Answer-Key/Final-Project-Solution/. Write the feature yourself first, then compare, or use a block when you are stuck on one file. Part of the code is shown with its surrounding file so that you can see where it belongs.

ViewModels/RollViewModel.swift. Add the filter state and the computed list below rollCount. history is unchanged.

Example — not part of the Dice Foundry project
    // nil means "show every die type"
    var historyFilter: DieType?

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

ContentView.swift. Replace historySection with this version. The Picker is bound to the view model's filter, the Clear button still reads the full history, and the list reads filteredHistory.

Example — not part of the Dice Foundry project
    private var historySection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("History")
                    .font(.title2)
                    .fontWeight(.bold)
                    .accessibilityAddTraits(.isHeader)
                Spacer()
                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)
                .accessibilityLabel("Filter history by die")
                Button("Clear") {
                    viewModel.clearHistory()
                }
                .disabled(viewModel.history.isEmpty)
                .accessibilityLabel("Clear history")
            }

            if viewModel.history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            } else if viewModel.filteredHistory.isEmpty {
                Text("No rolls match this filter")
                    .foregroundStyle(.secondary)
            }

            ForEach(viewModel.filteredHistory) { roll in
                HistoryRow(roll: roll)
                Divider()
            }
        }
    }

Ground rules

These apply to all three features:

  • Keep the existing project structure. New code goes in the folder that already owns that responsibility.
  • Do not change how HistoryStore saves or loads data, and do not rename or renumber existing enum raw values.
  • Keep views free of roll calculations, and keep the model free of colors, fonts and layout.
  • Keep the iOS 17.0 minimum deployment target and Swift 5 language mode. Do not add third-party packages.
  • Leave Chapter 12's DiceRoller injection and Chapter 13's view model structure in place.

Acceptance Criteria

Use this list to decide when each feature is done. Check each item by running the app or the tests, not by reading your code.

D100

  • The die picker shows seven dice: D4, D6, D8, D10, D12, D20 and D100.
  • The D100 button has a percent symbol that renders, and a VoiceOver label that reads as a 100-sided die.
  • Rolling one D100 produces one value between 1 and 100, and the notation reads 1D100.
  • Rolling five D100 with a modifier of -3 produces notation ending in - 3 and a total that equals the subtotal minus 3.
  • Over many rolls, values from 1 to 100 appear, and no value is ever 0 or 101.
  • A history file saved before this change still loads, and its rows look the same as before.

Maximum and minimum

  • Rolling a D20 many times produces some chips marked as natural maxima (20) and some as natural minima (1).
  • A D6 roll of 6 is marked as a natural maximum. A D100 roll of 100 is marked as a natural maximum.
  • A roll of 20 on a D20 with a modifier of +5 is still marked as a natural maximum, while its total shows 25.
  • A roll whose dice are all in the middle of the range shows no maximum or minimum marking, and its spoken description says nothing about them.
  • Each marking is visible without color: a user who cannot see the color difference can still tell which dice are marked.
  • The spoken description of a roll states how many dice are at maximum and how many are at minimum, when either count is more than zero.

History filter

  • With "All dice" selected, all rolls appear, newest first.
  • Selecting D20 shows only D20 rolls, and the rows keep their original order.
  • Selecting a die type with no rolls shows the "No rolls match this filter" message, not the "No rolls yet" message.
  • With no rolls at all, the message "No rolls yet" appears regardless of the filter.
  • Rolling while a filter is active still adds every new roll to the stored history, even when the new roll is hidden by the filter. The list shows it only when the filter matches.
  • Returning to "All dice" shows every roll again, including rolls made while the filter was active.
  • The filter returns to "All dice" when the app is relaunched. This is intentional for this chapter.

Clear and regression

  • Clear removes all saved history, including rolls the filter is hiding.
  • The Clear button is disabled when the full history is empty, and enabled when it is not, even if the filter currently shows no rows.
  • After a relaunch, the history shows the same rolls as before the relaunch, and the filter is "All dice".
  • Every Chapter 11 behavior still works: the spin animation, the haptic toggle, and the Dark and Light previews.
  • Existing tests still pass, and the new tests you write pass.

Suggested Implementation Order

Work through these steps in order. After each one, build with ⌘B and fix any error before moving on. The build is your first test.

  1. Add the D100 die. Start in Models/DieType.swift. Add the case, then let the compiler show you every switch that must handle it. Add the symbol and name behavior. Check the picker in the preview and run the app.
  2. Test the D100 die. Roll one D100 and five D100 with a modifier. Check the notation, the range and the history after a relaunch.
  3. Add the maximum and minimum rules to the model. In Models/RollResult.swift, add the two checks that answer "is this value a natural maximum?" and "is this value a natural minimum?". Keep them free of color and text. Decide whether each one takes a value as a parameter or works on a stored value, and be ready to say why.
  4. Show the markings in the result. In Views/ResultView.swift, use your model checks to style each chip, and add the non-color cue. Update the spoken description so it reports counts of maximum and minimum dice.
  5. Add the filter state to the view model. In ViewModels/RollViewModel.swift, add a filter that can be "no filter" or a specific die type, and a computed list of the history that the filter selects. Do not change history, and do not save the filter.
  6. Add the Picker to the history section. In ContentView.swift, add a Picker to the history header, bound to the filter. Show the list from the filtered history, and add the second empty-state message.
  7. Check the Clear button. Decide which list the Clear button's disabled state reads, and make Clear remove all history. Confirm it against the acceptance criteria.
  8. Write tests. Add tests in the DiceFoundryTests folder for the D100 range, the maximum and minimum checks, and the filter. Run them with ⌘U.
  9. Run the full manual test script in the next section, on the simulator, and compare every result with the acceptance criteria.

Hints

Hints for each required feature are in the companion document, ch14-exercises.md. Each feature has three hints, from a nudge to a close pointer. Read a hint only when you are stuck, and try the step again after each one.

The exercises document also contains extra practice exercises. They are not required for this chapter, but they are good preparation for the stretch goals.

Testing Instructions

Testing is part of the project, not an optional final step. Run each test in the order below, and write down anything that does not match.

Manual test script

Run the app on a recent iPhone simulator. Start from a clean history, so use Clear first if you already have rolls.

Step Action What you should see
1 Launch the app. The die picker shows seven dice, and the history says "No rolls yet".
2 Tap D100, set quantity to 1 and modifier to 0, and tap Roll Dice. One value from 1 to 100 appears, with notation 1D100.
3 Roll D20 ten times with modifier 0. Each result shows its chips. Any chip showing 20 or 1 is marked.
4 Set the modifier to +5 and roll D20 until a 20 appears. The chip for 20 is marked, and the total is 5 higher than the dice sum.
5 Roll D6 several times and open the filter. Choosing D6 shows only D6 rows, and choosing All dice restores them.
6 Choose a die you have not rolled. The "No rolls match this filter" message appears. The Clear button remains enabled.
7 Tap Clear while a filter is active. All rows disappear, and the "No rolls yet" message appears.
8 Roll some dice, stop the app from Xcode, and relaunch. The history returns, and the filter shows "All dice".
9 Turn on VoiceOver (Settings → Accessibility → VoiceOver, or the Accessibility Shortcut), and swipe to a result. The spoken description includes the maximum and minimum counts when they are above zero.

Turn VoiceOver off when you finish, and record which steps you ran and what you saw.

Unit tests

Add tests in the DiceFoundryTests folder. The reference solution has a test file named FinalProjectTests.swift, which you can use as a model for structure, but write your own tests first. Your tests should cover at least:

  • That the D100 die has 100 sides and the name D100.
  • That a large number of D100 rolls always stay within 1 to 100, using the default random source and then a predictable one.
  • That the maximum check is true for the highest face of each die type, and false for the other faces.
  • That the minimum check is true for 1 and false for other values.
  • That a filtered list contains only the matching die type, and that clearing the filter restores the full list.
  • That the history count is unchanged by applying a filter.

Test with the same test pattern from Chapter 12: a predictable random source, a temporary history file, and one behavior per test. Run the tests with ⌘U. Every test you add must pass before you commit.

DiceFoundryTests/FinalProjectTests.swift. This is the reference solution's test file. It is a new file, so it is shown in full. Write your own tests first and compare afterwards.

Example — not part of the Dice Foundry project
//
//  FinalProjectTests.swift
//  DiceFoundryTests
//

import Testing
import Foundation
@testable import DiceFoundry

@MainActor
struct FinalProjectTests {

    @Test func percentileDieHasOneHundredSides() {
        #expect(DieType.d100.sides == 100)
        #expect(DieType.d100.name == "D100")
        #expect(DieType.allCases.count == 7)
    }

    @Test func percentileRollsStayInRange() {
        let roller = DiceRoller()
        for _ in 1...200 {
            let roll = roller.roll(.d100, quantity: 10, modifier: 0)
            #expect(roll.values.allSatisfy { (1...100).contains($0) })
        }
    }

    @Test func maximumAndMinimumDetection() {
        let roll = RollResult(dieType: .d20, values: [20, 1, 12], modifier: 0)
        #expect(roll.isMaximum(20))
        #expect(!roll.isMaximum(12))
        #expect(roll.isMinimum(1))
        #expect(!roll.isMinimum(12))
    }

    @Test func historyFilterShowsOnlyMatchingDice() {
        let viewModel = RollViewModel(
            roller: DiceRoller(randomValue: { _ in 2 }),
            store: HistoryStore(fileURL: URL.temporaryDirectory.appending(path: "filter-\(UUID().uuidString).json"))
        )
        viewModel.selectedDie = .d6
        viewModel.roll()
        viewModel.selectedDie = .d20
        viewModel.roll()
        viewModel.roll()

        viewModel.historyFilter = .d20
        #expect(viewModel.filteredHistory.count == 2)

        viewModel.historyFilter = .d4
        #expect(viewModel.filteredHistory.isEmpty)

        viewModel.historyFilter = nil
        #expect(viewModel.filteredHistory.count == 3)
    }

    @Test func oldHistoryStillDecodesAfterAddingD100() throws {
        // A history file written before D100 existed must still load.
        // This JSON is in the format JSONEncoder wrote for RollResult in
        // Checkpoints 12 and 13: dieType is the Int raw value, and date is
        // seconds since the reference date (2001-01-01).
        let oldJSON = """
        [
          {
            "id": "11111111-1111-1111-1111-111111111111",
            "dieType": 6,
            "values": [4, 2, 6],
            "modifier": 2,
            "date": 800000000
          },
          {
            "id": "22222222-2222-2222-2222-222222222222",
            "dieType": 20,
            "values": [20],
            "modifier": -1,
            "date": 800000100.5
          }
        ]
        """
        let url = URL.temporaryDirectory.appending(path: "old-\(UUID().uuidString).json")
        defer { try? FileManager.default.removeItem(at: url) }
        try Data(oldJSON.utf8).write(to: url)

        let history = try HistoryStore(fileURL: url).load()

        #expect(history.count == 2)
        #expect(history[0].id == UUID(uuidString: "11111111-1111-1111-1111-111111111111"))
        #expect(history[0].dieType == .d6)
        #expect(history[0].values == [4, 2, 6])
        #expect(history[0].modifier == 2)
        #expect(history[0].total == 14)
        #expect(history[0].date == Date(timeIntervalSinceReferenceDate: 800000000))
        #expect(history[1].dieType == .d20)
        #expect(history[1].values == [20])
        #expect(history[1].modifier == -1)
        #expect(history[1].total == 19)
    }
}
Warning: A passing test proves only what it checks

A green checkmark means the code matches what the test expects. It does not mean the test expects the right thing. If your maximum-check test uses the same wrong logic as your code, it passes anyway. Write at least one test with a value you calculated by hand, not one you copied from your code's output.

Expected Results

Actual iOS Simulator screenshot — the final project in Light Mode after one 1D6 roll, with the D100 chip in the die picker

Actual iOS Simulator screenshot of the final project solution in Light Mode after one 1D6 roll, showing the D100 chip. Rolled numbers on your device will differ, and the examples below use other dice.

The mockups below show what you should see. They are drawn by hand from the requirements, not captured from the app, so the spacing and wording of your version may differ.

Illustrative mockup — not a screenshot. The die picker with seven dice, in three columns:

+-----------+-----------+-----------+
|  triangle |  square   |  diamond  |
|    D4     |    D6     |    D8     |
+-----------+-----------+-----------+
|  pentagon |  hexagon  |  octagon  |
|    D10    |    D12    |    D20    |
+-----------+-----------+-----------+
|  percent  |
|    D100   |
+-----------+

Illustrative mockup — not a screenshot. A roll of three D20 with a modifier of +5, showing the values 20, 7 and 1. The 20 is a natural maximum and the 1 is a natural minimum, and each carries a text cue as well as a color difference. The dice sum is 28, and 28 plus the modifier of 5 gives a total of 33:

                3D20 + 5
                 33
  [ 20 MAX ]   [  7  ]   [ 1 MIN ]
  Dice 28, modifier +5

Note: this is a rough sketch of the content, not a required design. Your layout, spacing and cue wording may differ. Check the numbers against the acceptance criteria, not against this mockup.

Illustrative mockup — not a screenshot. The history section with the filter set to D20, showing only D20 rows:

History                             [ Filter: D20 v ]  [ Clear ]
--------------------------------------------------------------
  D20   1D20 + 5                                          20
        15                                             9:41 AM
  -------------------------------------------------------------
  D20   2D20                                              24
        12, 12                                           9:38 AM

Illustrative mockup — not a screenshot. The history section when the filter matches nothing:

History                             [ Filter: D100 v ]  [ Clear ]
--------------------------------------------------------------
  No rolls match this filter

Stretch Goals

Complete the required features first. Each stretch goal is optional, and each one teaches something specific. Read the description, decide whether it fits your version of the app, and plan it before you type.

Favorites. Let the user mark a roll as a favorite, and show favorites in a filter of their own. This adds a Boolean to RollResult or a separate collection in the view model. Decide first whether a favorite is part of the saved data. If it is, changing RollResult changes the file format, so you must keep old files loadable. The Chapter 9 persistence rules apply.

Statistics screen. Show how many rolls the user has made, the average total for each die type, and the count of natural maxima and minima. Put the calculations in the model or a small helper with tests, and keep the screen to presentation. Consider whether the statistics should use the full history or the filtered history, and say which one you chose and why.

Sound preference. Add a second preference beside the haptic toggle, stored with @AppStorage the same way as hapticsEnabled. Playing a sound on iOS needs an audio framework, which this course does not cover. Keep the stretch goal to the preference and the decision of when a sound would play. Do not add audio code without first checking the framework's documentation for the iOS 17.0 minimum.

Configurable history limit. Replace the fixed history limit of 50 with a value the user can change, stored as a preference. This is harder than it looks. HistoryStore.maximumCount is a static let, and the view model trims the list against it. Changing the limit must trim the saved history correctly, and the limit must be read in one place. Write tests for the trimming, including the case where the new limit is smaller than the current history.

Self-Assessment Rubric

Score each area yourself. The answers document explains what a strong answer looks like for each one.

Area Strong Developing Not yet
Layer placement Each rule lives in the layer that owns it. The model answers maximum and minimum questions, and the view only decides how they look. Some logic sits in the view, but the feature works. Rules are copied into several views, or the view calculates rolls.
Enum change Every affected switch was found through the compiler, and no default hides a missing case. Every switch is updated, but a default was added to silence an error. A new case was added and some switch statements were not checked.
Filter state The filter is view model state, computed from history, and never copies or changes history. The filter works, but a second copy of the list is stored. The filter is computed in the view, or it changes stored history.
Accessibility Maximum and minimum are announced and visible without color. Announcements exist, but the chip cue relies on color. Neither the announcement nor a non-color cue exists.
Testing Tests cover the requirements, include a hand-calculated expectation, and pass with ⌘U. Tests pass but cover only the happy path. No tests were added, or tests were written to match the code's output.
Explanation You can explain each change, its file and why it is written that way, without looking at the code. You can explain most changes with help. You cannot explain why a change works.

Reading This Like a Developer

Read a feature the way the app runs it. Start from the entry point and follow data through the layers.

Where execution begins. The app starts in DiceFoundryApp.swift, where the @main attribute marks the entry point and the WindowGroup shows ContentView. Nothing in your new code runs until ContentView is created. Its body is then calculated, and SwiftUI reads the view model's properties while it builds the screen.

Which code runs on a button press. Tapping a die in the picker runs the closure in DieButton's action, which the DiePicker gave it. That closure writes the die into selectedDie through the binding. Tapping Roll Dice runs the button closure in ContentView, which calls viewModel.roll(). The roll itself is calculated by DiceRoller, which returns a RollResult. The view model then stores that result as the latest roll, increments rollCount, inserts it at the front of history, trims the list to the limit and saves it.

Which variables hold state. ContentView holds the view model in @State. The view model holds selectedDie, quantity, modifier, latestRoll, history, rollCount and, after this chapter, the history filter. Every value that changes the screen lives in the view model, not in a view.

Where a value originates and changes. The filter starts as nil in the view model. The Picker writes a new value into it through $viewModel.historyFilter. The filteredHistory property is computed each time it is read, from history and the filter. Nothing writes to filteredHistory, which is why it can never be out of step with the history.

How the interface responds to state changes. The view model is @Observable. When body reads a property, SwiftUI records the dependency. When that property changes, SwiftUI recalculates body. Choosing a new filter changes historyFilter, so the history section is recalculated and its ForEach shows the new list. Rolling changes rollCount, which triggers the haptic feedback and the spin in ResultView.

How data passes between views. ResultView receives the latest roll and the roll count as plain properties, so it can read them but not change them. DiePicker and RollOptionsView receive bindings, so they can change the view model's values. This one-way and two-way split is the Chapter 10 pattern, and your new code should follow it.

Where data is saved. HistoryStore writes the whole history array to roll-history.json in the app's Documents folder. The filter is not part of that file, and filtered lists are never saved. If you decide to save the filter, you add it to a different store, not to the history file.

How errors are handled. Loading and saving use do/try/catch in the view model, and failures are printed to the console. A missing history file is not an error; it means the user has no history yet. Your new features should keep that behavior. A filter cannot fail, so it has no error path.

Business logic versus presentation logic. "Is this value the natural maximum?" is business logic, and it belongs in RollResult. "Which color is a maximum chip?" and "What does VoiceOver say?" are presentation logic, and they belong in ResultView. "Which rows does the list show?" is a presentation decision based on state, and it belongs in the view model because it depends on state the user changes. When you are unsure which layer a rule belongs to, ask whether the rule would still be true if the app had no screen at all.

Reading This Like a Developer: Follow one roll from end to end

Put a breakpoint at the first line of roll() in RollViewModel, and step through the function with the debugger. Watch history.count before and after. Then continue into saveHistory() to see where the file is written. You have now followed a single user action through every layer of the app.

Troubleshooting

The errors below are the ones most likely in this chapter. The exact wording on your screen may differ slightly, so search for the key words rather than the whole message.

Switch must be exhaustive

A message similar to the following appears after you add the D100 case:

Switch must be exhaustive

Meaning. A switch over DieType does not handle every case. The compiler names the switch and the missing case, or points to the line.

Likely causes. You added case d100 but did not add a matching branch to a switch that returns a value for each die, such as the symbol name.

How to investigate. Click the error and read which case is missing. Then search the project for switch and check every switch over self in DieType.swift. Do not add a default: branch to make the error go away unless you have decided that a fallback value is correct for every future die.

The filter picker does not highlight the choice you made

Meaning. You choose a die in the Picker, the list does not change, or the Picker shows the wrong choice.

Likely causes. The selected value has no matching tag: for example, the "All dice" row is missing its typed nil tag, the tags use an unrelated type, or optional matching was disabled with includeOptional: false while using nonoptional tags. A nonoptional DieType tag is not automatically wrong in modern SwiftUI; optional matching is enabled by default. Another cause is a Picker bound to separate local @State instead of the view model's filter.

How to investigate. Check the type of the selection: value and the type of each .tag(...). Use the explicit optional tags shown in Syntax Breakdown to remove ambiguity, and make sure there is a tag for nil. Check that the Picker's binding starts with $viewModel. and that the view model property is a var, not a let. Read the console output while you change the filter.

Maximum and minimum markings are never shown

Meaning. Rolls that should show a natural maximum or minimum look like every other chip.

Likely causes. The check compares the total with the face value, or compares against the wrong number. The check may compare the value with the number of dice instead of the die's sides. The view may use the check, but the chip style may be overwritten by a later modifier in the chain.

How to investigate. Roll a D6 until you see a 6. Put a breakpoint inside your check, and print the die value and the die's sides. Confirm that the chip styling code runs for that value. Remember that modifier order matters (Chapter 3). A style applied to a parent view, or placed before a modifier that overrides it, can hide the one you meant to see.

A die's symbol is blank

Meaning. The picker shows a button with a label but no icon for the D100.

Likely causes. The SF Symbol name is misspelled. The compiler does not check symbol names, so a typo compiles and shows nothing.

How to investigate. Open Apple's SF Symbols app, search for the name you used, and copy the exact spelling into symbolName. Check every symbol you added, not only the new one.

History does not load after you changed DieType

Meaning. The history is empty after a relaunch, and the console prints a message similar to "Could not load roll history", followed by a decoding error.

Likely causes. An existing case's raw value was changed or removed, so saved rolls cannot be decoded. Adding a new case does not cause this. Changing case d6 = 6 to a different number does.

How to investigate. Compare the raw values in DieType.swift with the values you started with. Restore any changed value. Do not delete the history file to make the error go away unless you understand that doing so discards the user's history. The Chapter 9 section on decoding explains why raw values are part of the saved format.

The test fails with an expectation message

Meaning. A test reports that an expected value did not match the actual value.

Likely causes. Either the code is wrong or the expectation is. Your hand-calculated expectation may be wrong, or the test may use a random source that does not behave as you assumed.

How to investigate. Read which #expect line failed and what both values were. Work out the correct answer by hand for that input. If the code is wrong, fix the code. If the expectation is wrong, correct the test and write down why.

The clear button behaves unexpectedly with a filter

Meaning. Clear removes only some rows, or the button is disabled when rows are visible.

Likely causes. The Clear button's disabled state reads the filtered list, which is empty when the filter matches nothing. Clear may also call a function that removes only the filtered rows.

How to investigate. Compare the disabled expression with the acceptance criteria. The disabled state should depend on the full history, and Clear should remove all of it, as the acceptance criteria require.

Knowledge Check

  1. Why does the reference design put the natural maximum check in RollResult rather than in ResultView? Name one test you could write for the check without starting the app.
  2. The history filter is computed from history rather than stored as a second array. Describe one bug that a stored second array could cause, and explain how a computed property avoids it.
  3. You add case d100 to DieType. Explain why the compiler, rather than your memory, is the best tool for finding the places that must change, and when you would still want to read the code yourself.
  4. A Picker's selection is DieType?. What value must the "All dice" row select, and how do you write its explicit tag? Why can a nonoptional die tag also work in modern SwiftUI?
  5. A roll of 20 on a D20 with a modifier of +5 has a total of 25. Explain why the natural maximum marking should still apply to the 20 chip, and which property of RollResult you would use to check it.

Chapter Completion Checklist

  • I planned each feature by naming the layer that owns each rule before I edited any file.
  • I added the D100 die, and every switch over DieType handles it without a default that hides a missing case.
  • The die picker shows seven dice and the D100 symbol renders.
  • Rolls of D100 produce values from 1 to 100 and the notation is correct.
  • Natural maximum and minimum checks live in the model, and they evaluate individual die values, not totals.
  • The result view marks maximum and minimum chips with a cue that is not color alone.
  • The spoken description reports maximum and minimum counts when they are above zero.
  • The history filter state lives in the view model, uses nil for "All dice", and is not saved.
  • The filtered list is computed from history and never changes it.
  • The Picker has matching tags for each selection value, including nil, and the choice updates the list.
  • The two empty-state messages appear in the right situations.
  • Clear removes all history, including rows hidden by the filter.
  • A history file saved before my changes still loads.
  • I wrote tests for the new rules, one of which uses a hand-calculated expectation, and they pass with ⌘U.
  • I ran the manual test script on a simulator and recorded any step that did not match.
  • I can explain every change I made, its file and location, and why it is written that way.

Development Checkpoint

Commit your work so that you can return to the finished project. This is the last chapter, so the tag marks the end of the guided course.

In Xcode: Integrate → Commit... (the menu may be named Source Control in some versions), select all changed files, enter the message below, and commit. Or in Terminal, from your project folder:

git add -A
git commit -m "Chapter 14: Final project - D100, maximum and minimum, history filter"
git tag chapter-14

Do all of this on main. Do not create a challenge branch for the required features. If you tried an optional stretch goal, commit it on its own branch, such as git switch -c stretch-favorites, and merge it into main only after its tests pass and you are satisfied with it.

To compare your finished project with the reference, open 03-Solutions-and-Answer-Key/Final-Project-Solution/. It contains two folders, DiceFoundry/ and DiceFoundryTests/. Compare file by file with FileMerge (Xcode → Open Developer Tool → FileMerge) or with Terminal:

diff -ru 03-Solutions-and-Answer-Key/Final-Project-Solution/DiceFoundry \
  /path/to/your/DiceFoundry/DiceFoundry

Compare after you have finished and tested your version, not before. Differences in naming, comments and the order of properties are fine. Any difference in behavior is worth understanding. If the reference does something you did not expect, ask which of the two behaviors the acceptance criteria require, and record your reasoning.

Prediction Answers

Count the kept items. numbers.filter { $0 > 5 } keeps 8 and 15, because they are greater than 5. Its count is 2. The second expression, numbers.filter { $0 == 15 }.isEmpty, keeps only 15, so the filtered list is not empty and isEmpty is false.

Predict the two results. For [4, 6, 6], every item is 6 or less, so allSatisfy { $0 <= 6 } returns true. For [7, 2], the first item, 7, fails the test, so the result is false. allSatisfy stops at the first failing item, so it never looks at the 2 in that list. The earlier even-number example works the same way: [2, 5, 6] produces false because 5 fails, and [2, 4, 6] produces true.

What does Clear do with a filter active? Clear removes every roll in history, including the rolls the filter is hiding, and then saves the empty list. The filter itself is not changed, so after clearing, the list shows "No rolls yet" because there is no history at all. The Clear button is disabled in that state, because its disabled condition reads the full history, not the filtered list. If your version leaves the Clear button enabled with an empty history, or removes only the visible rows, compare your code with the acceptance criteria.