Dice Foundry Solutions and Answer Key

Chapter 11 Answers — Styling, Animation, and Accessibility

Knowledge Check Answers

1. Why asset catalog plus Theme instead of hex values in each view? The asset catalog stores each color once, with a light and a dark value, and iOS picks the right one automatically, including switching live when the appearance changes. Theme gives those colors role-based names (Theme.card, Theme.brass) so views express intent instead of raw values. To make brass warmer everywhere, you edit the two hex values of the Brass color set (and AccentColor, which uses the same values). Every view, gradient, and border that uses Theme.brass updates; no Swift code changes. With hex values scattered through views, you would have to find and edit every occurrence, and keep the light and dark versions in sync by hand.

2. Color(.brass) vs Color("Brass") after a rename. Color(.brass) uses a symbol Xcode generates from the color set's name. If the set is renamed, the symbol disappears and the code stops compiling with an error pointing at the exact line, so the mistake is found before the app runs. Color("Brass") is a string lookup: it compiles regardless, and at runtime the lookup fails, the view does not get the intended color, and the only sign is a console message. Compile-time errors are cheaper than runtime surprises.

3. Why rollCount and not latestRoll or roll.total? Two reasons rule out latestRoll: (a) it changes at launch, when loadHistory() sets it from the saved history, so the spin and haptic would fire every time the app opens; (b) RollResult is not Equatable, and both .onChange(of:) and .sensoryFeedback(trigger:) need a value they can compare. roll.total is ruled out because two consecutive rolls can have the same total, which is no change, so the second roll would not animate or buzz. rollCount changes exactly once per user roll and never at launch.

4. Why can the animation never change the rolled numbers? performRoll() calls rollDice(count:sides:), which calls Int.random(in:), builds a complete RollResult, assigns it to latestRoll, inserts it into history, and saves it, all before the view re-renders. spin() runs afterward in response to rollCount changing, and it only changes rotation, a visual angle owned by ResultView. It does not read or write any roll data. For accessibility, this means turning on Reduce Motion (which skips the spin) cannot change outcomes. For testing, it means the calculation is plain code that runs instantly and can be tested without any views or timing, which Chapter 12 relies on.

5. Why .cardStyle() in ContentView, and what does @ScaledMetric add? Applying the card style in the parent keeps components layout-neutral: ResultView draws its content and the screen that uses it decides the framing. The same component can then be reused in a context where a card would be wrong, without editing it. @ScaledMetric makes a number scale with the user's Dynamic Type setting; a fixed CGFloat stays the same size, so a 140-point circle could clip a total that has grown with larger text. With @ScaledMetric(relativeTo: .largeTitle), the circle and the number grow together.

Independent Challenge Solutions

Challenge 1 — A penalty color for negative modifiers

Solution folder: challenge-solutions/ch11-penalty-color/

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

Step 1 — Color set. In Assets.xcassets, add a Color Set named Penalty, set Appearances to Any, Dark, and enter:

Appearance Hex Contrast against CardBackground
Any (light) #A8322B 6.65:1 on #FFFFFF
Dark #F0A29A 6.65:1 on #292F36

Both comfortably exceed the 4.5:1 requirement for normal text. Build once (⌘B) so .penalty is generated.

Step 2 — Theme. In Theme/Theme.swift, inside enum Theme, after static let onBrass = Color(.onBrass):

Example — not part of the Dice Foundry project
    static let penalty = Color(.penalty)

Step 3 — ResultView. In Views/ResultView.swift, inside if roll.modifier != 0 { ... }, replace .foregroundStyle(.secondary) on the "Dice ..., modifier ..." text with:

Example — not part of the Dice Foundry project
                    Text("Dice \(roll.subtotal), modifier \(RollResult.formatModifier(roll.modifier))")
                        .foregroundStyle(roll.modifier < 0 ? Theme.penalty : Color.secondary)

Why it works: the color set gives an adaptive red that iOS swaps for Light and Dark Mode; Theme.penalty gives it a role name; the ternary picks it only for negative modifiers. Color.secondary is spelled out so both branches of the ternary are clearly Color. Because RollResult.formatModifier still produces "-3", the meaning is carried by the text as well as the color, which matters for color-blind users and VoiceOver (whose label for the result card is unchanged).

Alternatives: you could apply the color to the modifier stepper label in RollOptionsView as well, or show an SF Symbol such as minus.circle next to negative modifiers. If you only need a quick check, using the system .red would work, but it is not tuned to the palette and its contrast on the dark card is not guaranteed for small text; a custom color set keeps the design consistent.

Challenge 2 — Feedback when choosing a die

Solution folder: challenge-solutions/ch11-selection-feedback/

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The haptic itself was not tested on a physical device (see Optional Device Lesson D2).

Step 1 — Selection haptic. In ContentView.swift, inside body, directly after the existing roll .sensoryFeedback(...) { ... } block and before .onAppear:

Example — not part of the Dice Foundry project
        .sensoryFeedback(.selection, trigger: selectedDie) { _, _ in
            hapticsEnabled
        }

Step 2 — Reduce Motion property in DieButton. In Views/DieButton.swift, after let action: () -> Void, add a blank line and:

Example — not part of the Dice Foundry project
    @Environment(\.accessibilityReduceMotion) private var reduceMotion

Step 3 — Selection animation. In the same file, inside the Button's label closure, directly after the .overlay(...) that strokes the gold outline:

Example — not part of the Dice Foundry project
            .animation(reduceMotion ? nil : .snappy, value: isSelected)

Why it works: selectedDie is a DieType, an enum with an Int raw value, which Swift makes Equatable automatically, so it is a valid trigger. It only changes when the user taps a different die (it is never loaded from disk at launch), so the haptic does not play at launch or on roll. The condition closure reads the same hapticsEnabled preference, so one toggle controls both haptics. In DieButton, .animation(_:value:) animates the label's color, fill, and outline changes whenever isSelected flips; when Reduce Motion is on, the animation is nil, so the change is instant. Each DieButton reads the environment itself because environment values are available to any view that declares them.

Alternatives: you could wrap the selection change in withAnimation inside DiePicker's button action instead of using an implicit animation, but then DiePicker would need the Reduce Motion check too. A color fade is mild enough that some designers keep it even with Reduce Motion on (Reduce Motion is mainly about large movement); turning it off is the cautious choice the challenge asked for.

Challenge 3 — Audit and improve one element

There is no single solution; judge your answer by the acceptance criteria. A sample answer:

Problem: In the Accessibility Inspector, each history row reads "3D6 + 2, total 14. Dice: 4, 2, 6." Two rows with the same notation and total are indistinguishable by ear, while sighted users can tell them apart by time. Change: In HistoryRow, appended Rolled at \(roll.date.formatted(date: .omitted, time: .shortened)). to the accessibility label. Verification: Pointed the inspector at a history row before and after; the label now ends with the time. Checked Light and Dark previews; the visual layout is unchanged because only the accessibility label changed.

Other reasonable choices: adding .accessibilityHint("Vibrates when you roll dice.") to the toggle; checking that "Modifier: +20" wraps rather than truncates at the largest text sizes; increasing the studio name from .caption to .footnote. This challenge was not compile-tested because it has no fixed code.

Extra Practice Answers

Exercise 11.1 — Setting instead of adding

The circle visibly spins once. After roll 1, rotation changes from 0 to 360 inside withAnimation, so it animates one full turn. After rolls 2 and 3, spin() still runs (because rollCount changed), but it sets rotation to 360 when it is already 360. That is no change, so there is nothing to animate. rotation is 360, 360, 360. This is why the chapter's code uses rotation += 360: each roll produces a new value (360, 720, 1080) and every value is a multiple of 360, so the number ends upright.

Exercise 11.2 — The app buzzes at launch

loadHistory() runs in .onAppear and replaces history with the saved array. If there is saved history, history.count changes from 0 to, say, 12 at launch, which triggers the haptic. The trigger should be rollCount, which only performRoll() changes. This version has other false triggers too: tapping Clear changes history.count to 0 and buzzes; and once the history reaches 50, history.count stays at 50 after insert-and-trim (insert makes 51, removeLast() makes 50 again, within the same action), so rolls stop buzzing entirely at the history limit. A counter dedicated to "user rolled" avoids all of these.

Exercise 11.3 — Result decided in the animation

Problems include:

  1. Timing decides the outcome. The result is produced only when the animation finishes; interrupted or overlapping animations (tapping Roll twice quickly) can produce results in an unpredictable order, or not at all.
  2. Reduce Motion breaks or changes it. If the spin is skipped for Reduce Motion, the completion may run immediately or the code path may be skipped, so accessibility settings would affect the roll logic.
  3. Display and record disagree. For 0.6 seconds the screen shows the previous result while the user believes they rolled; history and saving would also have to be moved into the completion to stay in sync.
  4. Untestable. You cannot unit test the roll without running views and waiting for animations; Chapter 12's DiceRoller tests depend on the roll being plain code.
  5. It ignores the quantity (it always rolls one die) and duplicates logic that already exists in performRoll(); business logic has leaked into a presentation function.

The correct structure is the chapter's: calculate in performRoll(), then let the animation react to rollCount.

Exercise 11.4 — Corner radius 8

Change shape (they use Theme.cornerRadius): all five cards (background, border overlay) via cardStyle(), and the Roll Dice button's gradient background. Unchanged (they use literal radii): the die buttons (12), the result chips (8, already 8), and the result circle (a Circle, which has no corner radius). This is the intended split: page-level shapes follow the theme; small local shapes keep their own values.

Exercise 11.5 — Generated symbol names

Color(.cardBackground), Color(.onBrass), Color(.accent), and Color(.highlight). Xcode lowercases the first letter and drops a trailing "Color" from the name. This last rule is why naming a color set HighlightColor gives you .highlight, which surprises people who search for .highlightColor; if unsure, type Color(. and let autocomplete show the real names.