Dice Foundry Student Workbook

Chapter 11 — Styling, Animation, and Accessibility

At the end of Chapter 10 Dice Foundry worked well and its code was neatly split into components, but it still looked like a prototype: orange system buttons on a plain white page. In this chapter you give it the Dice Foundry visual identity (dark charcoal surfaces, brass and gold accents, rounded cards), make it look right in both Light and Dark Mode, add a short spin animation and a haptic tap when you roll, and make every control understandable to people who use VoiceOver, larger text, or Reduce Motion. You also give the app a real icon on the Home Screen.

This is the chapter where most AI-generated SwiftUI code gets messy. Colors get hard-coded in twenty places, animations get mixed into business logic, and accessibility is left out. You will see a disciplined alternative: colors live in one asset catalog, styling constants live in one small Theme type, the animation only reacts to a roll that has already happened, and each control describes itself to assistive technologies.

The chapter is longer than most because it covers three related topics (visual design, motion, and accessibility) plus the app icon. Take it in sittings: Part A and Part B (colors and theme) make a natural first session, Parts C to E a second, and Parts F and G (app icon and accessibility testing) a third.

Learning Objectives

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

  • Create named color sets in an asset catalog, give each one a light and a dark appearance, and enter exact hex values.
  • Use Xcode's generated color symbols, such as Color(.brass), and explain why they are safer than string names such as Color("Brass").
  • Collect design constants in an enum used as a namespace with static let properties.
  • Write a small extension on View that adds a reusable cardStyle() modifier, and decide when such a helper is justified.
  • Use RoundedRectangle, .background(_:in:), .overlay, .stroke, .shadow, and LinearGradient to build a card-based layout with consistent spacing.
  • Pin a button to the bottom of the screen with .safeAreaInset(edge: .bottom).
  • Animate a view with withAnimation, .animation(_:value:), .rotationEffect, and .contentTransition, triggered by a counter that changes only when the user rolls.
  • Explain why the random result must be calculated before, and independently of, any animation.
  • Add haptic feedback with .sensoryFeedback, controlled by a user preference stored with @AppStorage.
  • Add accessibility labels, hints, traits, and grouping so VoiceOver describes the app clearly.
  • Support Dynamic Type with text styles and @ScaledMetric, and respect Reduce Motion with @Environment(\.accessibilityReduceMotion).
  • Add an app icon with Any, Dark, and Tinted appearances, and verify it on the simulator's Home Screen.

Concept Explanation

Why styling deserves structure

Up to now you have written colors directly where you needed them: .foregroundStyle(.orange), .tint(.orange), Color.orange.opacity(0.2). That is fine while you are learning, and it is exactly what you will see in most quick AI-generated code. It stops being fine the moment you want to change the brand color, support Dark Mode properly, or keep five screens consistent. You would have to find every .orange and decide, one by one, what it should become.

Professional apps separate three things:

  1. Raw values (the actual colors, with their light and dark versions). These live in the asset catalog, a structured folder Xcode compiles into the app.
  2. Named design decisions ("the card background", "the accent used for highlights", "the standard corner radius"). These live in one Swift type, Theme.
  3. Usage (this text is brass, this card has the standard style). Views refer to Theme, never to raw hex values.

If you later decide brass should be a little warmer, you change one color set. If you decide cards should have sharper corners, you change one number. Nothing else moves.

Infrastructure Analogy: Configuration management for pixels

This is the same split you already use for infrastructure. The asset catalog is like an environment-specific variables file (one value for dev, another for prod; here, one value for Light Mode and one for Dark Mode). Theme is like a shared module that gives those variables meaningful names. Views are the resources that consume the module. You would never hard-code a production IP address into fifty scripts; for the same reason you do not hard-code a hex color into fifty views.

Asset catalogs and color sets

Assets.xcassets is an asset catalog: a folder with a special structure that Xcode shows as a visual editor. Inside it, each asset is itself a folder with a Contents.json file describing it. A color set (a folder ending in .colorset) holds one named color, and it can hold several appearances of that color:

  • Any Appearance: the default value, used whenever no more specific variant matches. In this project it is the Light Mode color.
  • Dark: used when the device is in Dark Mode.

When the app runs, iOS picks the right variant automatically and switches it live if the user changes appearance. You write Theme.card once, and the card is white in Light Mode and dark slate in Dark Mode. Colors that change like this are called adaptive colors. Apple's built-in semantic colors, such as .primary and .secondary text, are adaptive in the same way.

Why "Any, Dark" and not "Any, Light, Dark"? With three slots, the "Any" value is only used in situations that are neither light nor dark (rare on iPhone), so you would have to type the light color twice. With "Any, Dark", the "Any" slot doubles as the light value. Every color set in this project, including AccentColor once you edit it in Step 4, uses that arrangement.

Generated color symbols

Since Xcode 15, Xcode reads your asset catalog at build time and generates Swift code for it. For a color set named Brass it generates a static property you can write as .brass wherever a ColorResource is expected. That is why the project can write:

Example — not part of the Dice Foundry project
let typed = Color(.brass)      // generated symbol: checked by the compiler
let named = Color("Brass")     // string lookup: checked only at runtime

Both produce the same color when everything is spelled correctly. The difference shows up when something is wrong. If you rename the color set to BrassAccent, the first line stops compiling with a clear error ("type has no member 'brass'" or similar), and Xcode can autocomplete the valid names. The second line compiles happily; at runtime the lookup fails, the view does not get the color you intended, and the only clue is a message similar to "No color named 'Brass' found in asset catalog" in the console. The generated symbol turns a runtime surprise into a compile-time error, which is always the better trade.

Xcode builds the symbol name from the color set name: it lowercases the first letter (CardBackground becomes .cardBackground) and drops a trailing word "Color" (the template's AccentColor becomes .accent). The generated symbols only exist after a build, so you build once after creating color sets before you use them.

The Dice Foundry palette and how the light values were chosen

The Dice Foundry design is a dark "foundry" look: charcoal backgrounds, slightly lighter cards, and brass and gold for accents. Here is the full palette as it appears in the reference asset catalog.

Color set Role Dark appearance Any (light) appearance
BackgroundPrimary Top of the page background #171B20 #F4F0E6
BackgroundSecondary Bottom of the page background, die buttons, result circle #22282F #E8E1D2
CardBackground Card surfaces #292F36 #FFFFFF
Brass Main accent: icons, notation, selection, borders #C8A365 #8A6424
Gold Highlight: selection border, top of the brass gradient #E4BF7C #9C6F1E
OnBrass Text and icons drawn on top of brass #171B20 #FFFFFF
AccentColor App-wide tint used by system controls #C8A365 #8A6424

The dark values come straight from the Dice Foundry design brief. The light values were not invented by eye; they were chosen so the app stays readable:

  • Contrast ratio compares the brightness of two colors, from 1:1 (identical) to 21:1 (black on white). The Web Content Accessibility Guidelines (WCAG) ask for at least 4.5:1 for normal text and 3:1 for large text (roughly 18 point regular or 14 point bold and up) and for icons.
  • Brass text on a card measures 5.7:1 in Dark Mode (#C8A365 on #292F36) and 5.3:1 in Light Mode (#8A6424 on #FFFFFF). Bright brass #C8A365 on a white card would be far too faint, so the light brass is a darker, deeper version of the same hue.
  • Light backgrounds are warm off-whites (#F4F0E6, #E8E1D2) instead of pure gray, so the page still feels like the same brand. The light card is pure white so cards lift off the background.
  • OnBrass flips: dark charcoal on bright brass in Dark Mode (7.3:1), white on deep brass in Light Mode (5.3:1).
  • Body text is not a custom color at all. It uses the system's adaptive .primary (near-black in Light Mode, near-white in Dark Mode) and .secondary for captions. Apple tunes those for contrast, and they also respond to the user's Increase Contrast setting, which a hard-coded hex value would not.

Two honest caveats. First, the Roll button's label sits on a gradient that runs from gold to brass; in Light Mode, white on the gold end measures about 4.5:1. That is fine because the label is large and bold, so the 3:1 large-text threshold applies. Second, brass on BackgroundSecondary in Light Mode is about 4.1:1; the app only uses brass on that surface for borders and selected-die fills, not for small body text. If you add new text in brass, put it on a card, not on the secondary background.

Tip: Checking contrast yourself

You do not need to calculate contrast by hand. The Accessibility Inspector (covered in Part G) includes a color contrast calculator, and many free web tools accept two hex values. Check every new text/background pair in both appearances.

Shapes, borders, shadows, and gradients

SwiftUI draws decoration with ordinary views and modifiers:

  • RoundedRectangle(cornerRadius:) is a shape, like Circle() from Chapter 3, with rounded corners. Shapes can be filled (.fill(color)) or stroked (.stroke(color, lineWidth:), which draws only the outline).
  • .background(style, in: shape) paints a color or gradient behind a view, clipped to a shape. It is the cleanest way to give something a rounded background.
  • .overlay(view) draws a view on top of another view, sized to match it. A stroked rounded rectangle in an overlay is how you add a border that follows rounded corners.
  • .shadow(color:radius:x:y:) adds a soft drop shadow. Subtle shadows (low opacity, a few points of offset) suggest depth; heavy ones look dated.
  • LinearGradient(colors:startPoint:endPoint:) blends between colors along a line. It can be used anywhere a color can: as a background, a fill, or a stroke.

Consistent spacing

Visual polish is mostly consistency: the same corner radius on every card, the same gap between sections, the same inner padding. Dice Foundry keeps two numbers in Theme: cornerRadius = 16 and spacing = 20. Small internal gaps (4, 6, 8, 12 points) stay as literals inside individual components, because they are local layout details rather than design-system decisions. Making every number a constant is over-engineering; making the repeated, page-level numbers constants is good practice.

Extensions and the cardStyle() helper

Every section of the screen (die picker, options, result, history, settings) should look like a card: padding, full width, card background, rounded corners, a thin brass border, and a soft shadow. That is six modifiers, repeated five times. Repetition is the signal that a helper is justified.

Swift lets you add methods to an existing type with an extension. By extending View, you add a method that every SwiftUI view can call:

Example — not part of the Dice Foundry project
extension View {
    func cardStyle() -> some View {
        // apply the six card modifiers to self
    }
}

Now DiePicker(selection: $selectedDie).cardStyle() reads like any built-in modifier. One helper is justified here; turning every two-modifier combination into its own extension is not, because each helper is one more name the reader has to look up. A good rule: extract when the same group of modifiers appears three or more times and represents one design idea.

The project applies .cardStyle() in ContentView, not inside DiePicker or ResultView. That keeps the components layout-neutral: they draw their content and let the parent decide how they are framed. If you later reuse ResultView inside a sheet or a widget where a card would look wrong, it just works.

SwiftUI animation

In SwiftUI you do not move views frame by frame. You change state, and you tell SwiftUI to animate the change. SwiftUI then interpolates every animatable property (position, size, rotation, opacity, color) from the old value to the new value over time. There are two main ways to request this:

  • Explicit animation: wrap the state change in withAnimation(.someAnimation) { ... }. Every view affected by that change animates.
  • Implicit animation: attach .animation(.someAnimation, value: someValue) to a view. Whenever someValue changes, changes to that view animate.

Dice Foundry uses both. The result circle spins using withAnimation when a roll happens, and the total number "rolls" to its new value using an implicit .animation plus .contentTransition(.numericText(...)), which makes digits slide like an odometer.

Animation triggers

An animation needs a trigger: a value that changes exactly when the animation should run. The obvious candidate is latestRoll, but it is the wrong one, for two reasons:

  1. latestRoll is set at launch, when loadHistory() reads the saved history in .onAppear. If the spin and the haptic tap were triggered by latestRoll, the app would spin and buzz every time it opened, before the user touched anything.
  2. RollResult is not Equatable (Swift cannot compare two of them with ==), and both .onChange(of:) and .sensoryFeedback(trigger:) need a comparable value.

The total is not a good trigger either: if you roll 14 and then 14 again, the total did not change, so nothing would animate even though the user rolled. Instead, ContentView keeps a simple counter, rollCount, which increases by one inside performRoll() and nowhere else. It is never saved, it starts at 0 on each launch, and it changes exactly once per user roll. That makes it an ideal trigger for both the animation and the haptic.

Infrastructure Analogy: Edge-triggered, not level-triggered

rollCount is an event counter, like an interface's packet counter or a monotonically increasing sequence number. Monitoring alerts on "the counter increased", not on the current value. Using latestRoll would be like alerting on "a config file exists", which also fires at boot when the file is loaded from disk.

Keep the animation separate from the calculation

This is the most important idea in the chapter. The roll is calculated first, completely, in performRoll(): Int.random produces the values, a RollResult is created, it is stored in latestRoll, inserted into history, and saved to disk. Only after that does anything visual happen. The animation reacts to a result that already exists; it never produces one.

   USER TAPS "Roll Dice"
            |
            v
   performRoll()                       <-- business logic (ContentView for now)
     values = rollDice(...)            <-- Int.random happens HERE, once
     roll = RollResult(...)            <-- total, notation computed from values
     latestRoll = roll
     rollCount += 1                    <-- the trigger
     history.insert(roll, at: 0)
     saveHistory()                     <-- the result is final and on disk
            |
            |  state changed -> SwiftUI re-renders
            v
   +-------------------------------------------------------------+
   | PRESENTATION ONLY (reads the result, never changes it)      |
   |                                                             |
   |  ResultView .onChange(of: rollCount) -> spin()              |
   |       withAnimation { rotation += 360 }   (skipped if       |
   |                                            Reduce Motion)   |
   |  Text(total) .contentTransition(.numericText) digits slide  |
   |  ContentView .sensoryFeedback(trigger: rollCount)  haptic   |
   +-------------------------------------------------------------+

Why insist on this? Imagine the alternative many games use naively: show random faces while the die spins and "keep whatever it lands on". Then:

  • The result would depend on timing. Frame rate, device speed, or an interrupted animation could change which number is recorded.
  • Accessibility would change outcomes. With Reduce Motion on, there is no spin, so there would be nothing to land on.
  • The display and the record could disagree. History might store one number while the screen showed another for a frame.
  • You could not test it. In Chapter 12 you will move the random generation into a DiceRoller and test it with a predictable random source. That is only possible because the calculation is ordinary code that runs instantly, with no view or animation involved.
  • Fairness would be unclear. Int.random(in:) gives every face an equal chance. An animation-driven choice would give whatever distribution the animation code happens to produce.

So the rule is: calculate, then present. Animation is decoration on top of a finished result.

Haptic feedback

Haptics are the small, precise vibrations the iPhone's Taptic Engine produces, for example when you toggle a switch. SwiftUI (iOS 17 and later) offers .sensoryFeedback(_:trigger:): whenever the trigger value changes, the system plays the requested feedback. Dice Foundry plays a medium impact on each roll, again using rollCount as the trigger. Haptics are a preference (some people dislike them), so the app adds a toggle to turn them off.

Haptics do not play in the iOS Simulator; your Mac has no Taptic Engine. The course author verified that this code compiles and that the toggle works in the simulator, but did not test the haptic on hardware. To feel it on your own iPhone, follow Optional Device Lesson D2 after you finish this chapter.

@AppStorage and UserDefaults

In Chapter 9 you learned that UserDefaults is a small key-value store meant for preferences, not for data like roll history. SwiftUI's @AppStorage("key") property wrapper reads and writes one value in UserDefaults and, like @State, re-renders the view when the value changes. The haptics preference is a perfect fit: one Bool, stored under the key "hapticsEnabled", defaulting to true the first time the app runs. It survives app restarts automatically, with no save() call.

Accessibility: VoiceOver, Dynamic Type, Reduce Motion

Accessibility means people can use your app regardless of how they see, hear, or move. iOS does most of the work if you give it accurate information. This chapter covers the three features that affect Dice Foundry most:

  • VoiceOver is the built-in screen reader. The user moves through accessibility elements one at a time and VoiceOver speaks each element's label (what it is), value, traits (button, header, selected), and optional hint (what happens if you activate it). Standard controls describe themselves, but custom visuals need help: a die button that shows a square icon and "D6" should be read as "6-sided die, selected, button", not "square, D6".
  • Dynamic Type lets users choose a larger or smaller text size in Settings. Text that uses text styles such as .headline or .title2 scales automatically. Fixed-size elements (like the 140-point result circle) need @ScaledMetric so they grow with the text instead of clipping it.
  • Reduce Motion is a setting for people who experience discomfort or dizziness from motion. Apps should replace large movements (like a 360-degree spin) with no animation or a gentle fade. SwiftUI exposes the setting through the environment as accessibilityReduceMotion.
Important: What was and was not verified

The reference code for this chapter compiles with 0 errors and 0 warnings, and its appearance was checked in the iOS Simulator in Light and Dark Mode. The accessibility labels were written to follow Apple's guidance, but the course author did not listen to VoiceOver output by ear on a device, did not test every Dynamic Type size, and did not feel the haptics on hardware. Part G shows you how to check these yourself.

The SwiftUI environment

@Environment(\.someKey) reads a value that SwiftUI provides to every view: the color scheme, the locale, the current Dynamic Type size, accessibility settings, and more. You do not pass these values down manually; SwiftUI injects them, and when one changes (for example the user turns on Reduce Motion), every view that reads it re-renders.

Infrastructure Analogy: Environment variables for views

The SwiftUI environment is close to a process's environment variables: values set by the system above you, inherited by every child, read where needed. \.accessibilityReduceMotion is like reading REDUCE_MOTION=1 from the environment instead of having every caller pass a flag.

Syntax Breakdown

Generated color symbol: static let brass = Color(.brass)

Token Meaning
static The property belongs to the type Theme itself, not to an instance. You write Theme.brass. (You met static in Chapter 9 with HistoryStore.maximumCount.)
let A constant. The color reference never changes; the color it resolves to adapts to Light/Dark automatically.
brass The property name, lowercase like all Swift properties.
= Assigns the initial value.
Color( Creates a SwiftUI Color using the initializer that takes a ColorResource.
.brass The symbol Xcode generated from the Brass color set. The leading dot works because the initializer expects a ColorResource, so Swift looks for ColorResource.brass.
) Ends the initializer call.

Enum as a namespace: enum Theme { ... }

An enum with no cases cannot be instantiated: there is no value you could create. That makes it a convenient namespace, a named container for related constants. Theme.spacing reads clearly, nobody can accidentally write Theme(), and the constants are grouped in one file. You may see AI-generated code use struct Theme for the same purpose; it works, but a caseless enum states the intent better.

Extension: extension View { func cardStyle() -> some View { ... } }

Token Meaning
extension Adds members to an existing type without editing its original source.
View The type being extended. View is a protocol, so the method becomes available on every view.
func cardStyle() A new method, no parameters.
-> some View Returns "some specific view type" (the same opaque return type as body). The real type is a long nested modifier type you never need to write.
self Inside the method, the view you called it on. The method returns self with modifiers applied.

Shapes and decoration

Expression Meaning
RoundedRectangle(cornerRadius: 12) A rectangle shape with 12-point rounded corners. It expands to fill the space it is given.
.fill(Theme.brass) Paints the inside of a shape.
.stroke(Theme.gold, lineWidth: 2) Draws only the outline of a shape, 2 points wide.
.background(Theme.card, in: RoundedRectangle(...)) Paints Theme.card behind the view, clipped to the rounded shape.
.overlay(...) Draws the given view on top, sized to the modified view.
.shadow(color: .black.opacity(0.12), radius: 8, y: 4) Soft shadow: 12% black, blurred over 8 points, moved 4 points down. x is omitted, so it defaults to 0.
Theme.brass.opacity(0.35) The same color at 35% opacity.

LinearGradient(colors: [gold, brass], startPoint: .top, endPoint: .bottom)

Token Meaning
LinearGradient( A gradient that blends along a straight line.
colors: [gold, brass] An array of colors to blend, in order. Inside Theme you can refer to the other static properties by bare name.
startPoint: .top Where the first color is pure: the top edge (UnitPoint.top).
endPoint: .bottom Where the last color is pure: the bottom edge.

Explicit animation: withAnimation(.spring(duration: 0.6, bounce: 0.3)) { rotation += 360 }

Token Meaning
withAnimation( A function that runs the closure you give it and animates every view change that results.
.spring(duration: 0.6, bounce: 0.3) The animation curve: a spring that settles in about 0.6 seconds with a little overshoot (0 would be no bounce).
{ rotation += 360 } A trailing closure containing the state change. rotation is a @State Double; adding 360 means one full turn.

Implicit animation and content transitions

Expression Meaning
.contentTransition(.numericText(value: Double(roll.total))) When this Text's content changes inside an animation, animate digits like a counter. Passing the value lets SwiftUI decide whether digits roll up or down.
.animation(reduceMotion ? nil : .snappy, value: roll.total) Animate changes to this view whenever roll.total changes, using the quick .snappy curve, or nil (no animation) when Reduce Motion is on.
.rotationEffect(.degrees(rotation)) Draws the view rotated by rotation degrees around its center. Layout is unaffected; only the drawing rotates.
.onChange(of: rollCount) { spin() } Runs the closure whenever rollCount changes (not on first appearance). This is the iOS 17 form with a closure that takes no parameters.

@Environment(\.accessibilityReduceMotion) private var reduceMotion

Token Meaning
@Environment( Property wrapper that reads a value from the SwiftUI environment.
\.accessibilityReduceMotion A key path: a reference to a property by name (you saw \.self in ForEach). Here it names the environment value for the Reduce Motion setting.
private var reduceMotion The local name. Its type, Bool, is inferred from the key path. You read it; SwiftUI sets it.

@ScaledMetric(relativeTo: .largeTitle) private var circleSize: CGFloat = 140

Token Meaning
@ScaledMetric Property wrapper that scales a number with the user's Dynamic Type setting.
(relativeTo: .largeTitle) Scale at the same rate as the Large Title text style, so the circle grows in step with the big number inside it.
CGFloat The floating-point type SwiftUI uses for sizes and coordinates.
= 140 The size at the default text size. At larger settings the value increases automatically.

@AppStorage("hapticsEnabled") private var hapticsEnabled = true

Token Meaning
@AppStorage( Property wrapper backed by UserDefaults.standard.
"hapticsEnabled" The key under which the value is stored. Keep keys stable; renaming one loses the saved preference.
= true The default used only when nothing has been stored yet. The type (Bool) is inferred from it.
$hapticsEnabled The projected binding, passed to Toggle(isOn:) so the toggle can write the preference.

.sensoryFeedback(.impact(weight: .medium), trigger: rollCount) { _, _ in hapticsEnabled }

Token Meaning
.sensoryFeedback( Modifier that plays haptic feedback (iOS 17+).
.impact(weight: .medium) The kind of feedback: a physical "tap" of medium weight. Others include .selection, .success, .warning.
trigger: rollCount Play when this value changes.
{ _, _ in hapticsEnabled } A condition closure. SwiftUI passes the old and new trigger values; _, _ ignores both. The closure returns a Bool: play only if hapticsEnabled is true. Single-expression closures return their expression without return.

Accessibility modifiers

Modifier Meaning
.accessibilityLabel("Clear history") Replaces what VoiceOver says for this element.
.accessibilityHint("Rolls the selected dice...") Extra explanation VoiceOver reads after a pause, describing the result of activating it.
.accessibilityAddTraits(.isHeader) Marks the element as a heading so VoiceOver users can jump between sections.
.accessibilityAddTraits(isSelected ? .isSelected : []) Adds the "selected" trait only when selected. [] is an empty set of traits; traits are a set type, so "no traits" is written as an empty set literal.
.accessibilityHidden(true) Hides a purely decorative element from VoiceOver.
.accessibilityElement(children: .combine) Merges child elements into one, joining their labels.
.accessibilityElement(children: .ignore) Makes one element and ignores the children's labels; you supply the label yourself.

switch self in a computed property

Inside an enum's computed property, self is the current case. switch self { case .d4: return "triangle" ... } returns a different value for each case. Because the switch lists every case and has no default, the compiler will force you to update it if you add a case later (Chapter 14 adds D100), which is exactly the safety you want.

Layout and style odds and ends

Expression Meaning
.safeAreaInset(edge: .bottom) { ... } Places a view along the bottom edge and shrinks the scrollable area so content is never hidden behind it.
.background(.ultraThinMaterial) A translucent, blurred "frosted glass" background provided by the system; adapts to Light/Dark.
.ignoresSafeArea() Lets a view (here the background gradient) extend under the status bar and home indicator.
.buttonStyle(.plain) Removes the system button styling so your own background and colors show exactly as drawn.
Label("Roll Dice", systemImage: "dice.fill") A standard text-plus-icon view. VoiceOver reads only the text.
Toggle(isOn: $flag) { label } An on/off switch bound to a Bool.
.fontDesign(.serif) Uses the serif variant of the system font (New York) for a more classic title.
.textCase(.uppercase) / .tracking(2) Displays text in capitals and adds 2 points of letter spacing.
.font(.body.weight(.medium)) The Body text style (so it still scales with Dynamic Type) at medium weight.

Guided Implementation

The work is split into seven parts. The project builds at the end of every step unless a step warns you otherwise.

  • Part A — Color sets in the asset catalog (Steps 1–5)
  • Part B — The Theme file and cardStyle() (Steps 6–9)
  • Part C — Model additions for icons and accessibility (Steps 10–11)
  • Part D — Styling the components (Steps 12–16)
  • Part E — Animation in ResultView (Steps 17–23)
  • Part F — The new ContentView: header, cards, roll button, haptics, settings (Steps 24–32)
  • Part G — Adding an App Icon (Steps 33–38)
  • Part H — Testing appearance, Dynamic Type, Reduce Motion, and VoiceOver (Steps 39–43)

Before you start, open the project, make sure the Chapter 10 commit is in place (Integrate → Commit shows nothing to commit, or git status in Terminal shows a clean tree), and run the app once (⌘R) so you remember how it looks.

Part A — Color sets in the asset catalog

Step 1 — Look inside Assets.xcassets

In the Project navigator (⌘1), select Assets.xcassets. The editor changes to the asset catalog editor: a list of assets on the left and the selected asset on the right. The iOS App template created two assets for you in Chapter 1:

  • AccentColor: an empty color set used as the app-wide tint.
  • AppIcon: the app icon set, currently empty (you fill it in Part G).

The catalog's own Contents.json file (the one directly inside Assets.xcassets) already exists from the template; it only records the catalog format version, and you never edit it. Every asset you add in this part is written to disk as a folder with its own Contents.json, and Xcode keeps those files up to date as you click.

This is the complete text of the catalog's own Assets.xcassets/Contents.json at the end of the step; the template already wrote it, so you only compare it.

Example — not part of the Dice Foundry project
{
  "info": {
    "author": "xcode",
    "version": 1
  }
}
Infrastructure Analogy: It is just folders and JSON

Open Terminal and run ls on your project's DiceFoundry/Assets.xcassets folder after this part: you will see Brass.colorset, Gold.colorset and so on, each containing a small JSON file. That is good news for version control. Git diffs of color changes are readable, and a color set can be reviewed like any config file.

Step 2 — Create the BackgroundPrimary color set

Step 2 — Add the first color set

File: Assets.xcassets · Where: asset list · Action: Add (color set BackgroundPrimary)

Follow these clicks carefully; the remaining color sets repeat them.

  1. With Assets.xcassets selected, click the + button at the bottom of the asset list (or right-click in the list) and choose Color Set. A new asset called Color appears.
  2. Double-click its name and rename it to exactly BackgroundPrimary (capital B, capital P, no spaces). The name matters: Xcode generates the Swift symbol .backgroundPrimary from it.
  3. With the color set selected, open the Attributes inspector (⌥⌘4, or the right-most tab of the inspector, ⌥⌘0 to show the inspector).
  4. Find Appearances. Change it from None to Any, Dark. The editor now shows two color wells, labeled Any Appearance and Dark.
  5. Click the Any Appearance well. In the Attributes inspector, under Color, set Content to sRGB (it usually is already) and set Input Method to 8-bit Hexadecimal. A Hex field appears. Type #F4F0E6 and press Return.
  6. Click the Dark well and enter #171B20 the same way.

The two wells should now show a warm off-white and a near-black charcoal. If the wells look gray or the hex field reverts, check that you pressed Return after typing.

What this did, on disk, is create BackgroundPrimary.colorset/Contents.json containing both colors. You never need to type this file, but here is what it looks like so you know what Xcode is writing:

{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": { "alpha": "1.000", "blue": "0xE6", "green": "0xF0", "red": "0xF4" }
      },
      "idiom": "universal"
    },
    {
      "appearances": [ { "appearance": "luminosity", "value": "dark" } ],
      "color": {
        "color-space": "srgb",
        "components": { "alpha": "1.000", "blue": "0x20", "green": "0x1B", "red": "0x17" }
      },
      "idiom": "universal"
    }
  ],
  "info": { "author": "xcode", "version": 1 }
}

The first entry has no appearances key, so it is the "Any" value. The second entry is tagged with luminosity = dark. (The reference file spreads the components over several lines; formatting does not matter.)

This is the complete BackgroundPrimary.colorset/Contents.json at the end of the step, exactly as the reference checkpoint stores it.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0xE6",
          "green": "0xF0",
          "red": "0xF4"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x20",
          "green": "0x1B",
          "red": "0x17"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

Step 3 — Create the other five color sets

Step 3 — Add the remaining color sets

File: Assets.xcassets · Where: asset list · Action: Add (five color sets)

Repeat Step 2 for each row of this table. Every color set uses Appearances: Any, Dark, sRGB, 8-bit Hexadecimal input.

Color set name (exact) Any Appearance Dark
BackgroundSecondary #E8E1D2 #22282F
CardBackground #FFFFFF #292F36
Brass #8A6424 #C8A365
Gold #9C6F1E #E4BF7C
OnBrass #FFFFFF #171B20

When you finish, the asset list should contain AccentColor, AppIcon, BackgroundPrimary, BackgroundSecondary, Brass, CardBackground, Gold, and OnBrass (Xcode sorts them alphabetically).

This is the complete BackgroundSecondary.colorset/Contents.json at the end of the step, the file Xcode writes when you enter the hex values from the table.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0xD2",
          "green": "0xE1",
          "red": "0xE8"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x2F",
          "green": "0x28",
          "red": "0x22"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

This is the complete CardBackground.colorset/Contents.json at the end of the step, the file Xcode writes when you enter the hex values from the table.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0xFF",
          "green": "0xFF",
          "red": "0xFF"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x36",
          "green": "0x2F",
          "red": "0x29"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

This is the complete Brass.colorset/Contents.json at the end of the step, the file Xcode writes when you enter the hex values from the table.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x24",
          "green": "0x64",
          "red": "0x8A"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x65",
          "green": "0xA3",
          "red": "0xC8"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

This is the complete Gold.colorset/Contents.json at the end of the step, the file Xcode writes when you enter the hex values from the table.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x1E",
          "green": "0x6F",
          "red": "0x9C"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x7C",
          "green": "0xBF",
          "red": "0xE4"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

This is the complete OnBrass.colorset/Contents.json at the end of the step, the file Xcode writes when you enter the hex values from the table.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0xFF",
          "green": "0xFF",
          "red": "0xFF"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x20",
          "green": "0x1B",
          "red": "0x17"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}
Tip: Copy and paste color sets

You can select a finished color set, press ⌘C then ⌘V to duplicate it, rename the copy, and change its two hex values. This saves setting Appearances each time. Double-check the name of each copy; a duplicate is named something like BackgroundPrimary 1 until you rename it.

Step 4 — Set AccentColor to brass

Step 4 — Give the accent color the brass values

File: Assets.xcassets → AccentColor · Where: Attributes inspector · Action: Replace (empty color with brass values)

Select AccentColor, set Appearances to Any, Dark, and enter #8A6424 for Any Appearance and #C8A365 for Dark, exactly like Brass.

The accent color is the default tint for system controls throughout the app: the Stepper's plus and minus buttons, the Toggle's "on" color, the enabled Clear button. The build setting "Global Accent Color Name" in your target is already set to AccentColor by the template, which is how iOS knows to use it. Later you will also apply .tint(Theme.brass) in code; the two agree, and setting both means even system UI drawn outside your views (such as alerts) uses brass.

This is the complete AccentColor.colorset/Contents.json at the end of the step, now holding the brass values.

Example — not part of the Dice Foundry project
{
  "colors": [
    {
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x24",
          "green": "0x64",
          "red": "0x8A"
        }
      },
      "idiom": "universal"
    },
    {
      "appearances": [
        {
          "appearance": "luminosity",
          "value": "dark"
        }
      ],
      "color": {
        "color-space": "srgb",
        "components": {
          "alpha": "1.000",
          "blue": "0x65",
          "green": "0xA3",
          "red": "0xC8"
        }
      },
      "idiom": "universal"
    }
  ],
  "info": {
    "author": "xcode",
    "version": 1
  }
}

Step 5 — Build once to generate the symbols

Press ⌘B. The build should succeed with no changes to your Swift code. During this build Xcode reads the asset catalog and generates ColorResource symbols for each color set: .backgroundPrimary, .backgroundSecondary, .cardBackground, .brass, .gold, .onBrass, and .accent.

You will not see a new file in the Project navigator; the generated code lives in the build folder. You can confirm it worked in Step 6, where autocomplete will offer these names.

Note: If the symbols never appear

Generated asset symbols are controlled by the build setting Generate Swift Asset Symbol Extensions (ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS). Projects created with Xcode 15 or later have it set to Yes. If yours says No (for example, an older project), set it to Yes in the target's Build Settings and build again.

Part B — The Theme file and cardStyle()

Step 6 — Create the Theme folder and file with the colors

Step 6 — Create Theme.swift

File: Theme/Theme.swift (new) · Where: new folder Theme inside the DiceFoundry folder, next to Models, Persistence, and Views · Action: Create file

  1. In the Project navigator, right-click the DiceFoundry folder (the yellow folder containing ContentView.swift) and choose New Folder. Name it Theme.
  2. Right-click the new Theme folder and choose New File from Template... (the wording may be New File... in your Xcode version). Pick Swift File, click Next, name it Theme, make sure the DiceFoundry target is checked, and click Create.
  3. Replace the file's contents with the header comment, the import, and the start of the Theme enum:
Dice Foundry code
//
//  Theme.swift
//  DiceFoundry
//

import SwiftUI

enum Theme {
    // Colors come from the asset catalog, so each one has a light and a dark version.
    static let background = Color(.backgroundPrimary)
    static let backgroundSecondary = Color(.backgroundSecondary)
    static let card = Color(.cardBackground)
    static let brass = Color(.brass)
    static let gold = Color(.gold)
    static let onBrass = Color(.onBrass)
}

What it does: declares a caseless enum Theme that acts as a namespace, with one static let per color. Each one wraps a generated color symbol in a SwiftUI Color.

Why it is written this way:

  • import SwiftUI (not Foundation) because Color, LinearGradient, and View are SwiftUI types.
  • The Swift names are shorter and role-based where that reads better (Theme.card rather than Theme.cardBackground; Theme.background for the primary background). Views talk about roles, not hex values.
  • The comment records the one fact a future reader most needs: these colors are adaptive because they come from the asset catalog.

As you type Color(., autocomplete should list your color names. If it does not, build again (⌘B) and see Troubleshooting.

What should happen: press ⌘B; it should build. Nothing on screen changes yet, because no view uses Theme.

Step 7 — Add the layout constants

Step 7 — Add corner radius and spacing

File: Theme.swift · Where: inside enum Theme, after static let onBrass = Color(.onBrass) · Action: Add

Dice Foundry code
    static let cornerRadius: CGFloat = 16
    static let spacing: CGFloat = 20

What it does: adds the two page-level layout numbers. The explicit : CGFloat type annotation is needed because a bare 16 would be inferred as Int, and SwiftUI's radius and spacing parameters expect CGFloat.

Why only two: these are the numbers repeated across the whole screen (every card's corners, the gap between every card). Local numbers like a die button's 12-point corner radius stay in the component that uses them.

Leave a blank line before them, as in the reference, to separate colors from sizes.

Step 8 — Add the two gradients

Step 8 — Add the background and brass gradients

File: Theme.swift · Where: inside enum Theme, after static let spacing: CGFloat = 20 (still before the enum's closing brace) · Action: Add

Dice Foundry code
    static let backgroundGradient = LinearGradient(
        colors: [background, backgroundSecondary],
        startPoint: .top,
        endPoint: .bottom
    )

    static let brassGradient = LinearGradient(
        colors: [gold, brass],
        startPoint: .top,
        endPoint: .bottom
    )

What it does: backgroundGradient fades from BackgroundPrimary at the top of the screen to BackgroundSecondary at the bottom, giving the page subtle depth. brassGradient runs from the lighter gold to brass, like light catching a metal bar; it is used for the Roll button and the ring around the result.

Why it is written this way: inside Theme, background and gold refer to the static properties declared above, so the gradients automatically adapt to Light and Dark Mode too. Splitting the arguments over several lines, one per argument, is the usual Swift formatting when a call does not fit comfortably on one line.

Step 9 — Add the cardStyle() extension

Step 9 — Add the reusable card modifier

File: Theme.swift · Where: after the closing brace of enum Theme, at the end of the file · Action: Add

Dice Foundry code
extension View {
    func cardStyle() -> some View {
        self
            .padding()
            .frame(maxWidth: .infinity)
            .background(Theme.card, in: RoundedRectangle(cornerRadius: Theme.cornerRadius))
            .overlay(
                RoundedRectangle(cornerRadius: Theme.cornerRadius)
                    .stroke(Theme.brass.opacity(0.35), lineWidth: 1)
            )
            .shadow(color: .black.opacity(0.12), radius: 8, y: 4)
    }
}

What it does, modifier by modifier (remember from Chapter 3 that order matters; each modifier wraps the result of the previous one):

  1. self is the view .cardStyle() was called on.
  2. .padding() adds the standard inner margin so content does not touch the card edge.
  3. .frame(maxWidth: .infinity) makes every card the full available width, so cards line up even when their content is narrow.
  4. .background(Theme.card, in: RoundedRectangle(...)) paints the card color behind the padded, full-width view, clipped to rounded corners. Because it comes after padding and frame, the background covers the padding too.
  5. .overlay(...) draws a rounded outline on top with the same corner radius, in 35% brass, 1 point wide: a thin border that reads as a brass edge in Dark Mode and a faint warm line in Light Mode.
  6. .shadow(...) adds a soft shadow under the whole card.

Why the border is an overlay and not .border(...): SwiftUI's .border draws a square-cornered rectangle, which would poke out past the rounded background. A stroked RoundedRectangle in an overlay follows the corners exactly.

What should happen: press ⌘B; it should build. You have defined cardStyle() but not called it yet.

Reading This Like a Developer: Where does cardStyle() come from?

When you see an unfamiliar modifier like .cardStyle() in someone else's code, Option-click it (⌥-click) or Control-Command-click it to jump to its definition. If it is defined in an extension View, it is project code, not SwiftUI. AI-generated projects often contain dozens of these; knowing to check is half the battle.

Part C — Model additions for icons and accessibility

The die buttons and history rows will show a small shape icon for each die type, and VoiceOver needs a spoken name for each die. Both are facts about the die type, so they belong on DieType, next to name, instead of being worked out in each view.

Step 10 — Add accessibilityName to DieType

Step 10 — Add a spoken name for each die

File: Models/DieType.swift · Where: inside enum DieType, after the closing brace of var name: String · Action: Add

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

What it does: returns a phrase such as "6-sided die" or "20-sided die".

Why: VoiceOver would read the visual label "D6" as something like "D 6", which is jargon to many listeners. "6-sided die" is unambiguous. Keeping it on the model means every view that needs a spoken name gets the same wording.

Step 11 — Add symbolName with a switch on self

Step 11 — Map each die to an SF Symbol

File: Models/DieType.swift · Where: inside enum DieType, after accessibilityName · Action: Add

Dice Foundry code
    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"
        }
    }

What it does: returns the name of an SF Symbol (Apple's built-in icon set, which you have used since Chapter 1 with "dice") that suggests each die's shape. A D4 is a pyramid of triangles, a D6 a cube of squares, and so on. Exact shapes for D10, D12, and D20 do not exist in SF Symbols, so the mapping simply uses polygons with more sides for dice with more faces.

Why switch self: self is the case this property is being asked about. Because the switch is exhaustive (it lists all six cases and has no default), adding a seventh die type later produces a compile error right here, reminding you to choose its icon. A default branch would silently give new dice some generic icon.

Predict Before You Run: Trace the model

What do DieType.d12.accessibilityName and DieType.d12.symbolName return? And which symbol does DieType.d8.symbolName return? Write your answers down, then check Prediction Answers at the end of the chapter.

What should happen: press ⌘B. It should build. Nothing visible changes yet.

Part D — Styling the components

Now apply the palette to each component, starting with the smallest.

Step 12 — Restyle the DieButton label

Step 12 — Give each die button an icon and a themed background

File: Views/DieButton.swift · Where: inside body, the label closure of Button(action: action) { ... } · Action: Replace

Before (Chapter 10):

Example — not part of the Dice Foundry project
        Button(action: action) {
            Text(dieType.name)
                .font(.headline)
                .frame(maxWidth: .infinity)
        }

After:

Dice Foundry code
        Button(action: action) {
            VStack(spacing: 6) {
                Image(systemName: dieType.symbolName)
                    .font(.title2)
                Text(dieType.name)
                    .font(.headline)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 12)
            .foregroundStyle(isSelected ? Theme.onBrass : Color.primary)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(isSelected ? Theme.brass : Theme.backgroundSecondary)
            )
            .overlay(
                RoundedRectangle(cornerRadius: 12)
                    .stroke(isSelected ? Theme.gold : Color.clear, lineWidth: 2)
            )
        }

What it does:

  • The label is now a small vertical stack: the shape icon above the "D6" text.
  • .frame(maxWidth: .infinity) and .padding(.vertical, 12) make each button fill its grid column with a comfortable height (well over Apple's recommended 44-point minimum touch target).
  • .foregroundStyle(...) colors both icon and text: OnBrass when selected (dark on bright brass in Dark Mode, white on deep brass in Light Mode), otherwise the system's adaptive .primary text color.
  • The background is a filled rounded rectangle: brass when selected, the secondary background otherwise.
  • The overlay adds a 2-point gold outline only when selected. Color.clear draws nothing but keeps the view structure identical in both states, which makes the change smooth.

Why Color.primary and Color.clear are spelled out: both branches of a ternary must have the same type. Theme.onBrass is a Color, so writing Color.primary makes it explicit that the other branch is a Color too. In some contexts Swift can infer .primary on its own, but the explicit form avoids confusing "mismatching types" errors and reads more clearly.

Why .background(RoundedRectangle(...).fill(...)) here but .background(color, in: shape) in cardStyle(): the two forms draw the same thing. The in: form is shorter when you have one color; the shape form is handy when you want to treat the shape as a view (fill it, stroke it, combine it). You will see both in real code, so the project uses both.

The project will not look quite right yet: the old .buttonStyle(.bordered) and .tint are still applied after this closure, so the system draws its own gray or orange bordered button behind your design. The next step fixes that. It still builds.

Step 13 — Use a plain button style and describe the button to VoiceOver

Step 13 — Replace the system styling with plain style and accessibility

File: Views/DieButton.swift · Where: directly after the closing brace of the Button, replacing .buttonStyle(.bordered) and .tint(isSelected ? .orange : .gray) · Action: Replace

Before:

Example — not part of the Dice Foundry project
        .buttonStyle(.bordered)
        .tint(isSelected ? .orange : .gray)

After:

Dice Foundry code
        .buttonStyle(.plain)
        .accessibilityLabel(dieType.accessibilityName)
        .accessibilityAddTraits(isSelected ? .isSelected : [])

What it does:

  • .buttonStyle(.plain) tells SwiftUI not to add any button chrome. The button still behaves like a button (tappable, highlighted briefly when pressed, announced as a button), but it looks exactly like your label.
  • .accessibilityLabel(dieType.accessibilityName) replaces what VoiceOver would otherwise read (the symbol name and "D6") with "6-sided die".
  • .accessibilityAddTraits(isSelected ? .isSelected : []) adds the Selected trait to the chosen die. VoiceOver then says something like "6-sided die, selected, button". Selection was only shown by color before, and color alone is invisible to VoiceOver users and hard to see for some color-blind users.

What should happen: open the canvas (⌥⌘↩) on DieButton.swift. The preview shows a brass D6 with a square icon next to a neutral D20 with an octagon. Try the canvas's color scheme control (in the canvas's bottom bar, often called Canvas Device Settings or Variants) to see Dark Mode.

Step 14 — Tidy RollOptionsView

Step 14 — Add spacing, a divider, and a medium font weight

File: Views/RollOptionsView.swift · Where: the body property · Action: Replace

Before:

Example — not part of the Dice Foundry project
        VStack {
            Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
            Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: -20...20)
        }

After:

Dice Foundry code
        VStack(spacing: 12) {
            Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
            Divider()
            Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: -20...20)
        }
        .font(.body.weight(.medium))

What it does: adds 12 points of spacing and a thin divider between the two steppers, and sets their labels to the Body style at medium weight. .font on the VStack applies to the text inside it, because font is an environment value that children inherit.

Why .body.weight(.medium) and not .system(size: 17, weight: .medium): the text style .body scales with Dynamic Type; a fixed size would not. Whenever you set a font, start from a text style.

There is no card background here. RollOptionsView stays layout-neutral; ContentView will wrap it with .cardStyle() in Part F. The Stepper's plus and minus buttons pick up the brass accent color you set in Step 4.

Step 15 — Add the die icon to HistoryRow

Step 15 — Show the die shape at the start of each history row

File: Views/HistoryRow.swift · Where: inside body, as the first child of the HStack, before VStack(alignment: .leading) · Action: Add

Dice Foundry code
            Image(systemName: roll.dieType.symbolName)
                .font(.title3)
                .foregroundStyle(Theme.brass)
                .frame(width: 32)

What it does: shows the die's shape in brass at the leading edge of the row. The fixed width: 32 keeps the notation text aligned in a neat column regardless of how wide each symbol is.

Why data flows this way: HistoryRow already receives a RollResult; the result knows its dieType, and the die type knows its symbolName. The row just follows that chain. No new property is needed.

Step 16 — Make each history row one VoiceOver element

Step 16 — Combine the row into a single spoken sentence

File: Views/HistoryRow.swift · Where: after the closing brace of the outer HStack, still inside body · Action: Add

Dice Foundry code
        .accessibilityElement(children: .ignore)
        .accessibilityLabel("\(roll.notation), total \(roll.total). Dice: \(roll.valuesDescription).")

What it does: without these lines, VoiceOver would visit four or five separate pieces per row (the icon, "3D6 + 2", "4, 2, 6", "14", "3:42 PM"), and the user would have to swipe through each. .accessibilityElement(children: .ignore) turns the whole row into one element and ignores the children's individual labels; .accessibilityLabel(...) supplies one sentence instead, such as "3D6 + 2, total 14. Dice: 4, 2, 6."

Why .ignore instead of .combine: .combine would join the children's labels automatically, including the time and the icon's name, in visual order. Writing the label yourself lets you put the most important information (the total) first and leave out noise. The time is omitted on purpose: it is useful visually but rarely what a listener is looking for. That is a judgment call; you could add it.

What should happen: ⌘B builds. The HistoryRow preview shows a brass octagon next to "2D20 - 4".

Part E — Animation in ResultView

ResultView gets the most changes: new colors, a ring around the total, a numeric transition, a spin, Dynamic Type scaling, Reduce Motion support, and a VoiceOver description. You will start with the trigger, which lives in ContentView.

Step 17 — Add the rollCount trigger to ContentView

Step 17a — Add the counter

File: ContentView.swift · Where: inside struct ContentView, after @State private var history: [RollResult] = [] · Action: Add

Dice Foundry code
    @State private var rollCount: Int = 0
Step 17b — Increase it once per roll

File: ContentView.swift · Where: inside performRoll(), directly after latestRoll = roll · Action: Add

Dice Foundry code
            rollCount += 1

The surrounding code in performRoll() now reads:

Dice Foundry code
            let values = rollDice(count: quantity, sides: selectedDie.sides)
            let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
            latestRoll = roll
            rollCount += 1
            history.insert(roll, at: 0)

What it does: rollCount is a plain counter that goes 0, 1, 2, 3... each time the user rolls during this launch.

Why here and only here: as explained in the Concept Explanation, rollCount must change exactly when a user roll happens. loadHistory() sets latestRoll at launch but does not touch rollCount, and clearHistory() does not touch it either. Notice also where in performRoll() it sits: after the values have been generated and the RollResult created. By the time anything reacts to rollCount, the result is already final.

What should happen: ⌘B builds. Nothing visible changes; nothing reads rollCount yet.

Step 18 — Pass rollCount into ResultView

This step touches two files, because adding a stored property to ResultView changes its initializer. Do all three edits before building; after only the first one, the project will not build (Xcode reports a missing argument for rollCount in each place ResultView is created).

Step 18a — Add the property

File: Views/ResultView.swift · Where: inside struct ResultView, after let roll: RollResult? · Action: Add

Dice Foundry code
    let rollCount: Int
Step 18b — Update the two previews

File: Views/ResultView.swift · Where: the two #Preview blocks at the end of the file · Action: Replace

Dice Foundry code
#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()
}

The previews pass a fixed rollCount because they only show a still picture. .padding() keeps the ring from touching the canvas edge. (The "With a roll" preview uses the course's worked example: 3D6 + 2 rolling 4, 2, 6 for a total of 14.)

Step 18c — Update the call in ContentView

File: ContentView.swift · Where: inside body, the line ResultView(roll: latestRoll) · Action: Replace

Dice Foundry code
                ResultView(roll: latestRoll, rollCount: rollCount)

What it does: ResultView now receives the counter as a plain, read-only property (one-way data flow, as in Chapter 10). It does not need a @Binding, because it never changes the count; it only reacts when the count changes.

What should happen: ⌘B now builds again.

Step 19 — Add the environment, scaled metrics, and rotation state

Step 19 — Add four properties to ResultView

File: Views/ResultView.swift · Where: after let rollCount: Int, separated by a blank line, before private let resultColumns · Action: Add

Dice Foundry code
    @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

What each one is:

  • reduceMotion is true when the user has turned on Settings → Accessibility → Motion → Reduce Motion. SwiftUI keeps it current.
  • totalSize is the font size of the big total: 56 points at the default text size, larger when the user picks a larger text size.
  • circleSize is the diameter of the result circle: 140 points by default, scaled the same way so the number always fits inside it.
  • rotation is the circle's current rotation in degrees. It is @State owned by ResultView because it is purely visual: no other view needs it, and it is not part of the roll.

Why @State here is fine even though Chapter 10 moved state up to ContentView: the rule is "put state in the lowest view that needs it". The roll data is needed by several views, so it lives in the parent. The spin angle is needed only by this view, so it lives here.

Step 20 — Restyle the notation and the result circle

Step 20a — Color the notation brass

File: Views/ResultView.swift · Where: inside if let roll { ... }, on the Text(roll.notation), after .fontWeight(.semibold) · Action: Add

Dice Foundry code
                    .foregroundStyle(Theme.brass)
Step 20b — Replace the orange circle with a ringed, animated one

File: Views/ResultView.swift · Where: the ZStack { ... } inside if let roll · Action: Replace

Before:

Example — not part of the Dice Foundry project
                ZStack {
                    Circle()
                        .fill(Color.orange.opacity(0.2))
                        .frame(width: 140, height: 140)
                    Text("\(roll.total)")
                        .font(.system(size: 64, weight: .bold))
                }

After:

Dice Foundry code
                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))

What it does, layer by layer:

  1. A filled circle in the secondary background color: the face of the "coin".
  2. A second circle, stroked with the brass gradient, 4 points wide: a metal rim. A gradient works as a stroke style exactly like a color.
  3. The total, in a bold rounded font at the scaled size. design: .rounded gives friendlier digits.
  4. .contentTransition(.numericText(value:)) plus .animation(..., value: roll.total): when the total changes, the digits slide to the new number like an odometer instead of snapping. With Reduce Motion on, the animation is nil, so the number changes instantly.
  5. The frame moved from the first circle to the whole ZStack and now uses circleSize, so both circles and the text share one scaled size.
  6. .rotationEffect(.degrees(rotation)) rotates the whole stack, rim and number together, by the current rotation. Right now rotation is always 0; Step 23 changes it.

Why .system(size: totalSize, ...) is acceptable even though Step 14 said to prefer text styles: a fixed point size does not scale with Dynamic Type, but totalSize is not fixed. It is a @ScaledMetric, so it grows with the user's setting. This is the standard way to get a custom large size that still respects Dynamic Type.

Note: Why the numeric transition needs a value

.numericText(value:) uses the number to decide the direction of the digit animation (counting up versus down). roll.total is an Int, and the parameter is a Double, so it is converted with Double(roll.total), the same conversion you used in Chapter 2.

Step 21 — Restyle the result chips

Step 21 — Use theme colors, a border, and a minimum size for each die value

File: Views/ResultView.swift · Where: inside the ForEach in the LazyVGrid, the modifiers after .fontWeight(.semibold) on Text("\(roll.values[index])") · Action: Replace

Before:

Example — not part of the Dice Foundry project
                            .frame(width: 44, height: 44)
                            .background(Color.orange.opacity(0.2))
                            .clipShape(RoundedRectangle(cornerRadius: 8))

After:

Dice Foundry code
                            .frame(minWidth: 44, minHeight: 44)
                            .background(Theme.backgroundSecondary, in: RoundedRectangle(cornerRadius: 8))
                            .overlay(
                                RoundedRectangle(cornerRadius: 8)
                                    .stroke(Theme.brass.opacity(0.5), lineWidth: 1)
                            )

What it does: each die value sits on a rounded secondary-background tile with a thin brass border.

Why minWidth/minHeight instead of fixed width/height: at large Dynamic Type sizes a two-digit .title3 number is wider than 44 points. A fixed frame would clip it or squeeze it; a minimum frame lets the chip grow while keeping the 44-point minimum. The grid already uses .adaptive(minimum: 44) columns, so chips wrap neatly.

Why .background(_:in:) replaced .background plus .clipShape: the old code painted a square background and then clipped the whole view to a rounded shape. The new form paints the background directly in the rounded shape and clips nothing, so the overlay border is not cut off at the corners.

Step 22 — Improve the empty state

Step 22 — Show an icon with the "Tap Roll Dice" prompt

File: Views/ResultView.swift · Where: the else { ... } branch of if let roll · Action: Replace

Before:

Example — not part of the Dice Foundry project
            } else {
                Text("Tap Roll Dice to begin")
                    .foregroundStyle(.secondary)
                    .frame(height: 140)
            }

After:

Dice Foundry code
            } else {
                VStack(spacing: 8) {
                    Image(systemName: "dice")
                        .font(.largeTitle)
                        .foregroundStyle(Theme.brass)
                    Text("Tap Roll Dice to begin")
                        .foregroundStyle(.secondary)
                }
                .frame(minHeight: circleSize)
            }

What it does: a brass dice icon above the prompt, with a minimum height equal to the circle's size so the card does not jump much in height when the first roll appears. minHeight instead of height again lets it grow with large text.

Step 23 — Add the VoiceOver description, the spin, and the trigger

First add the two helpers, then the modifiers that use them, so the project builds after each part.

Step 23a — Add the accessibility description and the spin function

File: Views/ResultView.swift · Where: inside struct ResultView, after the closing brace of body · Action: Add

Dice Foundry code
    private var accessibilityDescription: String {
        if let roll {
            return "Rolled \(roll.notation). Total \(roll.total). Dice: \(roll.valuesDescription)."
        } else {
            return "No roll yet. Tap Roll Dice to begin."
        }
    }

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

What it does:

  • accessibilityDescription builds the one sentence VoiceOver will read for the whole result card, for example "Rolled 3D6 + 2. Total 14. Dice: 4, 2, 6." It uses the if let roll shorthand from Chapter 10.
  • spin() checks Reduce Motion first. If it is on, the function returns immediately: no spin. Otherwise it adds 360 degrees to rotation inside withAnimation, so SwiftUI animates the circle through one full turn with a slightly bouncy spring.

Why rotation += 360 and not rotation = 360: setting it to 360 would work for the first roll, but the second roll would "change" 360 to 360, which is no change, so nothing would animate. Adding 360 each time always produces a new value (360, 720, 1080...), and because every value is a multiple of 360 the number always ends upright.

Why this is presentation logic only: spin() reads nothing from the roll and changes nothing about it. Delete it, and every roll still produces the same values, total, history entry, and saved file.

Step 23b — Attach the modifiers to the outer VStack

File: Views/ResultView.swift · Where: inside body, after the closing brace of the outer VStack(spacing: 16) { ... } · Action: Add

Dice Foundry code
        .frame(maxWidth: .infinity)
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(accessibilityDescription)
        .onChange(of: rollCount) {
            spin()
        }

What it does:

  • .frame(maxWidth: .infinity) makes the result fill the card's width so its content stays centered.
  • .accessibilityElement(children: .ignore) and .accessibilityLabel(...) make the entire result card one VoiceOver element that reads accessibilityDescription, instead of a scattered list of numbers.
  • .onChange(of: rollCount) { spin() } runs spin() every time rollCount changes. It does not run when the view first appears, which is why launching the app (and loading saved history) never spins anything.
Predict Before You Run: How far has it turned?

Reduce Motion is off. The app launches with saved history, so latestRoll is set from disk. The user then taps Roll Dice three times. What is rotation in ResultView after the third roll? What would it be if Reduce Motion had been on the whole time? Check Prediction Answers.

What should happen: open the canvas on ResultView.swift. The "With a roll" preview shows "3D6 + 2" in brass, a ringed circle with 14, and three bordered chips 4, 2, 6. Previews do not show the spin, because nothing changes rollCount in a static preview. You will see the spin when you run the app after Part F.

Part F — The new ContentView

ContentView gets a header, cards around every section, a roll button pinned to the bottom, a settings card with the haptics toggle, and the haptic itself. You will add the new computed properties first, then rewrite body to use them.

Step 24 — Add the haptics preference

Step 24 — Store the haptics setting in UserDefaults

File: ContentView.swift · Where: after @State private var rollCount: Int = 0, with a blank line before and after, above private let store = HistoryStore() · Action: Add

Dice Foundry code
    @AppStorage("hapticsEnabled") private var hapticsEnabled = true

What it does: declares a Bool preference stored in UserDefaults under the key "hapticsEnabled". The first time the app runs the key does not exist, so the value is true. When a toggle changes it, @AppStorage writes the new value to UserDefaults immediately and re-renders the view.

Why @AppStorage and not the JSON history file: this is exactly the "small preference" case Chapter 9 described. One Bool does not need a file, an encoder, or error handling. The roll history, by contrast, is user data that can grow to 50 entries, so it stays in the JSON file.

Infrastructure Analogy: A tiny key-value config store

UserDefaults is a per-app key-value store, similar to a small registry hive or a defaults domain on macOS (which it literally is: the simulator stores it as a .plist file in the app's Library/Preferences folder). @AppStorage is a watcher bound to one key: read on access, write on change, reconcile the UI after every change.

Step 25 — Add the header

Step 25 — Create a header with the app name and studio name

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of body, before private var historySection · Action: Add

Dice Foundry code
    private var header: some View {
        VStack(spacing: 4) {
            HStack {
                Image(systemName: "dice.fill")
                    .font(.title)
                    .foregroundStyle(Theme.brass)
                    .accessibilityHidden(true)
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .fontDesign(.serif)
            }
            Text("The Black Well Foundry")
                .font(.caption)
                .textCase(.uppercase)
                .tracking(2)
                .foregroundStyle(.secondary)
        }
        .accessibilityElement(children: .combine)
        .accessibilityAddTraits(.isHeader)
    }

What it does: the title row from earlier chapters (now brass and in a serif font), with a small, spaced-out, uppercase studio name below it. Use your own studio name if you like; it is only text.

Accessibility details:

  • The dice icon is decoration, so .accessibilityHidden(true) stops VoiceOver from announcing it.
  • .accessibilityElement(children: .combine) merges the remaining texts into one element, read as "Dice Foundry, The Black Well Foundry".
  • .accessibilityAddTraits(.isHeader) marks it as a heading, so a VoiceOver user can use the rotor to jump straight to it.

Here .combine is the right choice (compare .ignore in Step 16) because the children's own text is exactly what should be read.

Step 26 — Add the roll button as a property

Step 26 — Build a full-width brass roll button

File: ContentView.swift · Where: after the closing brace of header · Action: Add

Dice Foundry code
    private var rollButton: some View {
        Button {
            performRoll()
        } label: {
            Label("Roll Dice", systemImage: "dice.fill")
                .font(.title2)
                .fontWeight(.bold)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 16)
                .foregroundStyle(Theme.onBrass)
                .background(Theme.brassGradient, in: RoundedRectangle(cornerRadius: Theme.cornerRadius))
        }
        .buttonStyle(.plain)
        .accessibilityHint("Rolls the selected dice and adds the result to your history.")
    }

What it does: a full-width button with a gold-to-brass gradient, rounded with the standard corner radius, labeled with a dice icon and "Roll Dice" in large bold OnBrass text. The action still calls the same performRoll() as before; only the presentation changed.

Why Button { } label: { }: you used this form in Chapter 5. It is needed because the label is a custom view, not a plain string. Label gives a properly spaced icon-plus-text pair, and VoiceOver reads only "Roll Dice" from it (the icon is decorative by default inside a Label).

Why a hint: the label says what the button is; the hint says what will happen. VoiceOver reads hints after a short pause, and users can turn hints off, so never put essential information only in a hint.

Step 27 — Add the settings section

Step 27 — Add a haptics toggle

File: ContentView.swift · Where: after the closing brace of historySection, before private func rollDie(sides: Int) -> Int · Action: Add

Dice Foundry code
    private var settingsSection: some View {
        Toggle(isOn: $hapticsEnabled) {
            Label("Haptic feedback", systemImage: "iphone.radiowaves.left.and.right")
        }
    }

What it does: an on/off switch labeled "Haptic feedback" with an icon of a phone giving off vibrations. $hapticsEnabled is the binding projected by @AppStorage, just as $quantity is the binding projected by @State. Flipping the toggle writes UserDefaults, which re-renders ContentView, which changes what the haptic's condition closure (Step 31) returns.

The toggle's "on" color comes from the accent color, so it is brass.

Step 28 — Mark up the history section for VoiceOver

Step 28a — Make "History" a heading

File: ContentView.swift · Where: inside historySection, on Text("History"), after .fontWeight(.bold) · Action: Add

Dice Foundry code
                    .accessibilityAddTraits(.isHeader)
Step 28b — Give the Clear button a clearer spoken label

File: ContentView.swift · Where: inside historySection, after .disabled(history.isEmpty) · Action: Add

Dice Foundry code
                .accessibilityLabel("Clear history")

The HStack at the top of historySection now reads:

Dice Foundry code
            HStack {
                Text("History")
                    .font(.title2)
                    .fontWeight(.bold)
                    .accessibilityAddTraits(.isHeader)
                Spacer()
                Button("Clear") {
                    clearHistory()
                }
                .disabled(history.isEmpty)
                .accessibilityLabel("Clear history")
            }

Why: on screen, "Clear" is obviously about history because it sits next to the "History" title. A VoiceOver user who swipes straight to the button hears only "Clear, button" without that visual context. "Clear history, button" is self-explanatory. When the history is empty, VoiceOver also reports the button as dimmed, thanks to .disabled.

Step 29 — Rewrite the main stack with cards

Step 29 — Use the header, cards, and theme spacing; remove the old Roll button

File: ContentView.swift · Where: inside body, the VStack(spacing: 20) { ... } inside the ScrollView (keep .padding() after it) · Action: Replace

Before (Chapter 10, shortened):

Example — not part of the Dice Foundry project
            VStack(spacing: 20) {
                HStack {
                    Image(systemName: "dice.fill")
                    ...
                }

                DiePicker(selection: $selectedDie)

                RollOptionsView(quantity: $quantity, modifier: $modifier)

                ResultView(roll: latestRoll, rollCount: rollCount)

                Button("Roll Dice") {
                    performRoll()
                }
                .font(.title2)
                .buttonStyle(.borderedProminent)
                .controlSize(.large)
                .tint(.orange)

                historySection
            }

After:

Dice Foundry code
            VStack(spacing: Theme.spacing) {
                header

                DiePicker(selection: $selectedDie)
                    .cardStyle()

                RollOptionsView(quantity: $quantity, modifier: $modifier)
                    .cardStyle()

                ResultView(roll: latestRoll, rollCount: rollCount)
                    .cardStyle()

                historySection
                    .cardStyle()

                settingsSection
                    .cardStyle()
            }

What it does:

  • The inline title HStack is replaced by the header property from Step 25.
  • Every section gets .cardStyle(), so the page becomes a column of five matching cards separated by Theme.spacing (20 points, the same number as before, now with a name).
  • The old orange Button("Roll Dice") is deleted from the scrolling content. It comes back in Step 30, pinned to the bottom of the screen.
  • settingsSection is added as the last card.

Why the cards are applied here, not inside each component: this is the layout-neutral rule from the Concept Explanation. ContentView decides that, on this screen, each section is a card. The components only decide what they look like inside.

What should happen: ⌘B builds, but if you run now there is no Roll button at all. That is expected; do Step 30 next.

Step 30 — Background, tint, and the pinned roll button

Step 30 — Add page-level modifiers to the ScrollView

File: ContentView.swift · Where: inside body, directly after the closing brace of ScrollView { ... } and before .onAppear { loadHistory() } · Action: Add

Dice Foundry code
        .background(Theme.backgroundGradient.ignoresSafeArea())
        .tint(Theme.brass)
        .safeAreaInset(edge: .bottom) {
            rollButton
                .padding(.horizontal)
                .padding(.vertical, 8)
                .background(.ultraThinMaterial)
        }

What it does:

  • .background(Theme.backgroundGradient.ignoresSafeArea()) paints the charcoal (or warm off-white) gradient behind the whole scroll view. .ignoresSafeArea() is applied to the gradient, not to the content, so the color reaches under the status bar and the Home indicator while the cards stay inside the safe area.
  • .tint(Theme.brass) sets the tint for every control inside: steppers, the Clear button, the toggle. It matches the asset catalog's AccentColor; setting it in code too makes the intent visible in the source.
  • .safeAreaInset(edge: .bottom) { ... } places the roll button along the bottom edge and, importantly, adds that much inset to the scroll view's safe area. The last card can scroll fully above the button instead of hiding behind it. The .ultraThinMaterial background gives the bar a frosted look so content scrolling underneath is softly blurred.

Why the button moved out of the scroll view: the roll button is the app's primary action. When history grows, a button in the middle of the scroll content scrolls away. Pinned at the bottom, it is always under the user's thumb.

AI-Assisted Development: Spotting fragile layouts in AI-generated code

A common AI-generated pattern for a bottom button is a ZStack with the ScrollView underneath and the button aligned to the bottom on top, sometimes with a hard-coded .padding(.bottom, 100) on the content so the last item is not hidden. It works on the device the prompt was tested on and breaks with larger text or a different screen size. .safeAreaInset handles it in one modifier. When you review AI code, look for magic padding numbers that compensate for an overlay; they usually mean a better layout tool exists. When you direct an AI agent, name the tool: "pin the button with .safeAreaInset(edge: .bottom) and keep colors in Theme" gets you code that matches your project instead of a new style each time.

Step 31 — Add the haptic

Step 31 — Play a tap on every roll, if enabled

File: ContentView.swift · Where: directly after the .safeAreaInset(edge: .bottom) { ... } block from Step 30, before .onAppear · Action: Add

Dice Foundry code
        .sensoryFeedback(.impact(weight: .medium), trigger: rollCount) { _, _ in
            hapticsEnabled
        }

What it does: every time rollCount changes, SwiftUI calls the condition closure. The closure receives the old and new values of rollCount (ignored with _, _) and returns hapticsEnabled. If it returns true, the phone plays a medium impact tap; if false, nothing happens.

Why the condition closure instead of an if around the modifier: modifiers are not statements, so you cannot wrap one in a plain if inside a modifier chain without creating two different view structures. The condition closure is SwiftUI's built-in way to say "only sometimes". It is evaluated at the moment the trigger changes, so flipping the toggle takes effect on the very next roll.

Why rollCount again: the same reasoning as the spin. It changes only on user rolls, never at launch, and it changes even when two rolls in a row have the same total.

Again notice the order of events: performRoll() generates the values, builds the RollResult, sets latestRoll, and then increases rollCount. The haptic, like the spin, is a reaction to a result that already exists.

Your body now ends like this:

Dice Foundry code
        .sensoryFeedback(.impact(weight: .medium), trigger: rollCount) { _, _ in
            hapticsEnabled
        }
        .onAppear {
            loadHistory()
        }
    }

Step 32 — Add Light and Dark previews

Step 32 — Preview both appearances side by side

File: ContentView.swift · Where: the #Preview block at the end of the file · Action: Replace

Dice Foundry code
#Preview("Light") {
    ContentView()
}

#Preview("Dark") {
    ContentView()
        .preferredColorScheme(.dark)
}

What it does: two named previews. .preferredColorScheme(.dark) forces Dark Mode for the second one, so the canvas shows a "Light" and a "Dark" tab (or both at once, depending on your canvas layout). Naming previews with a string makes the tabs readable.

What should happen now: press ⌘R. The app should open in whichever appearance your simulator uses (simulators default to Light). You should see the header, five cards, and the brass Roll Dice bar at the bottom. Tap Roll Dice: the circle spins once with a little bounce, the total's digits slide to the new value, and a history row appears with a brass die icon. Roll several times and scroll: the history scrolls under the frosted bar, and the last card can always be scrolled above it. Flip the haptics toggle; in the simulator you feel nothing either way, but the setting is remembered after you stop (⌘.) and relaunch (⌘R).

Reading This Like a Developer: Where execution begins for the spin

Put a breakpoint (click the line number gutter) on rotation += 360 in ResultView.spin() and on rollCount += 1 in performRoll(), then roll. The debugger stops first in performRoll(), where the result is already computed, and only afterward in spin(). Chapter 12 covers breakpoints in depth; for now, just press Continue (⌃⌘Y) each time it stops, then remove the breakpoints by dragging them out of the gutter.

Part G — Adding an App Icon

So far Dice Foundry has shown a blank placeholder on the Home Screen. In this part you add a real icon, with a variant for each Home Screen appearance.

Step 33 — Understand what an app icon is and where iOS shows it

An app icon is the image that represents your app everywhere outside the app itself: on the Home Screen, in the App Library, in Spotlight search results, in Settings (next to your app's settings, if it has any), in notifications, in the app switcher, and, when you publish, on the App Store. iOS displays it at many sizes, from about 60 points across on the Home Screen down to around 20 points in some lists.

Since Xcode 14 you supply one 1024 × 1024 pixel image and Xcode generates every smaller size during the build. The image lives in the AppIcon set inside Assets.xcassets. The build setting Primary App Icon Set Name (ASSETCATALOG_COMPILER_APPICON_NAME) is already AppIcon in your target, so whatever you put in that set becomes the app's icon.

Starting with iOS 18, people can choose how Home Screen icons look: the normal (light) style, a Dark style, or a Tinted style where every icon is recolored in a single hue they pick. An icon set can therefore hold three images:

Slot in Xcode Used when What the image should be
Any Appearance (default) Normal Home Screen; also always on iOS 17 A complete, opaque icon with its own background
Dark User chose Dark icons (iOS 18+) The artwork on a transparent background; iOS supplies a dark backdrop
Tinted User chose Tinted icons (iOS 18+) A grayscale version on a transparent background; iOS colors it with the user's tint

Because Dice Foundry's minimum target is iOS 17.0, keep in mind that iOS 17 devices always show the default (Any Appearance) icon. If you leave Dark or Tinted empty, iOS 18 and later derive a version automatically from the default icon, usually less attractively than one you designed.

Step 34 — Find the supplied icon files

The course folder includes a ready-made icon in App-Icon/:

File Description Goes in
AppIcon-Light.png 1024 × 1024, opaque charcoal background (the app's #22282F→#171B20 gradient) with a brass, faceted D20 in the center Any Appearance
AppIcon-Dark.png 1024 × 1024, the same brass D20 on a transparent background Dark
AppIcon-Tinted.png 1024 × 1024, a grayscale D20 on a transparent background Tinted
Source-SVG/AppIcon-*.svg Editable vector sources for all three (not added to Xcode)

They were created for this course; you are free to use or modify them. If you want to check the files' properties before using them, macOS's sips tool will tell you:

cd path/to/DiceFoundryCourse/App-Icon
sips -g pixelWidth -g pixelHeight -g hasAlpha AppIcon-Light.png AppIcon-Dark.png

You should see 1024 × 1024 for each, hasAlpha: no for AppIcon-Light.png (correct: the default icon must be opaque), and hasAlpha: yes for the Dark file (correct: it needs transparency).

Step 35 — Show the Any, Dark, and Tinted wells

Step 35 — Prepare the AppIcon set

File: Assets.xcassets → AppIcon · Where: asset catalog editor and Attributes inspector · Action: Replace (set appearances)

  1. Select Assets.xcassets in the Project navigator, then select AppIcon in the asset list.
  2. Look at the editor. Recent Xcode versions create the AppIcon set with three empty wells already visible, labeled something like Any Appearance, Dark, and Tinted, under an iOS heading.
  3. If you see only one well, open the Attributes inspector (⌥⌘4) with AppIcon selected. Under iOS, make sure the size option is Single Size, and set Appearances to Any, Dark, Tinted. The two extra wells appear.

Step 36 — Drag the three PNGs into their wells

Step 36 — Add the icon images

File: Assets.xcassets → AppIcon · Where: the three image wells · Action: Add

  1. In Finder, open the course's App-Icon folder and arrange the window so you can see Xcode's AppIcon editor.
  2. Drag AppIcon-Light.png onto the Any Appearance well.
  3. Drag AppIcon-Dark.png onto the Dark well.
  4. Drag AppIcon-Tinted.png onto the Tinted well.

Each well should now show its image. Xcode copies each file into the AppIcon.appiconset folder of your project (you do not need to keep the originals in place) and records it in the set's Contents.json. You never edit that file by hand, but it is worth knowing what correct looks like. The reference checkpoint's file reads:

{
  "images" : [
    {
      "filename" : "AppIcon-Light.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    },
    {
      "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ],
      "filename" : "AppIcon-Dark.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    },
    {
      "appearances" : [ { "appearance" : "luminosity", "value" : "tinted" } ],
      "filename" : "AppIcon-Tinted.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    }
  ],
  "info" : { "author" : "xcode", "version" : 1 }
}

Like color sets, the default entry has no appearances key, and the other two are tagged dark and tinted. If a filename line is missing for a slot, that well is empty. (Xcode may name the copied files differently, for example after the original file name or with a numeric suffix; the names do not matter as long as each slot has a filename.)

This is the complete AppIcon.appiconset/Contents.json at the end of the step, with all three images recorded.

Example — not part of the Dice Foundry project
{
  "images" : [
    {
      "filename" : "AppIcon-Light.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    },
    {
      "appearances" : [
        {
          "appearance" : "luminosity",
          "value" : "dark"
        }
      ],
      "filename" : "AppIcon-Dark.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    },
    {
      "appearances" : [
        {
          "appearance" : "luminosity",
          "value" : "tinted"
        }
      ],
      "filename" : "AppIcon-Tinted.png",
      "idiom" : "universal",
      "platform" : "ios",
      "size" : "1024x1024"
    }
  ],
  "info" : {
    "author" : "xcode",
    "version" : 1
  }
}

The rules your icon images must follow, whether you use the supplied files or your own:

  • PNG, exactly 1024 × 1024 pixels. Xcode shows a warning on the asset if the size is wrong.
  • No transparency in the default (Any Appearance) icon. iOS fills transparent areas with black, and App Store submission rejects default icons with an alpha channel. The Dark and Tinted images are the exception: they are expected to be transparent.
  • Square corners. Do not round the corners or add your own mask. iOS applies its own rounded-rectangle shape (and on newer versions, its own edge treatment). Pre-rounded artwork ends up with dark slivers in the corners.
  • No drop shadow or border around the whole icon. The system draws whatever framing it needs.

Step 37 — Verify on the simulator Home Screen

  1. Build and run (⌘R). The app opens as usual.
  2. Go to the Home Screen: press ⇧⌘H, or choose Device → Home from the Simulator menu bar.
  3. Find Dice Foundry (swipe to the next page if needed, or swipe down on the Home Screen and search). It should show the brass D20 on a charcoal background, with the name "Dice Foundry" you set as the display name in Chapter 1.

Here is roughly what to expect:

Illustrative mockup — not a screenshot

   +--------+   +--------+   +--------+   +--------+
   | Maps   |   | Photos |   |Settings|   | ###### |
   |  icon  |   |  icon  |   |  icon  |   | # /\ # |   <- charcoal tile,
   +--------+   +--------+   +--------+   | #/__\# |      brass D20
     Maps         Photos      Settings    +--------+
                                         Dice Foundry
Actual iOS Simulator screenshot — the Dice Foundry icon on the Home Screen

Actual iOS Simulator screenshot of the Home Screen with the Dice Foundry icon, a dark rounded square with a gold d20 marked 20. Your other apps and wallpaper will differ.

Warning: The old icon can be cached

The simulator's Home Screen (SpringBoard) caches app icons. If you still see the blank placeholder after adding the icon, stop the app (⌘.), go to the Home Screen, long-press the Dice Foundry icon, choose Remove App → Delete App, and run again from Xcode (⌘R). Deleting the app also deletes its saved roll history and the haptics preference in the simulator. That is fine for testing; your code recreates both.

Step 38 — Preview the Dark and Tinted icons (iOS 18 and later)

On a simulator running iOS 18 or later:

  1. On the Home Screen, long-press an empty area until the icons jiggle.
  2. Tap Edit in the top-left corner, then Customize.
  3. Choose Dark. Dice Foundry should switch to the version with the brass D20 on the system's dark backdrop.
  4. Choose Tinted and pick a color. Your grayscale artwork is recolored in that tint.
  5. Switch back to the default (Light, or Automatic) when you are done.

Newer iOS versions may show additional styles in this menu (for example, clear or glass-like styles). They work from the same icon images, and the wording of the menu may differ slightly from these steps.

On an iOS 17 simulator there is no Customize option; the default icon is always used.

Note: Icon Composer and .icon files (optional)

Xcode 26 and later include Icon Composer (Xcode → Open Developer Tool → Icon Composer), a separate app for building layered icons saved as .icon files. Layered icons let the system render depth, specular highlights, and the translucent "Liquid Glass" look introduced in iOS 26. You add the .icon file to the project and name it as the app icon. It is the direction Apple is moving, but it is not required: the single-size PNG approach used in this course still works on current iOS versions and is what you will meet in most existing projects. Try Icon Composer once you are comfortable with the basics.

Designing your own icon

When you design an icon for one of your own apps, these guidelines keep it professional:

  • Work in vector at 1024 × 1024. Use any vector tool (Figma, Sketch, Affinity Designer, Illustrator, or even a hand-edited SVG like the course's Source-SVG files), then export PNGs. Vector art stays sharp and is easy to recolor for the Dark and Tinted variants.
  • One strong silhouette. A single, bold shape (here, a D20) is recognized instantly. Several small objects turn into noise.
  • Check it small. Shrink your export to about 60 pixels wide (roughly the Home Screen size) and to 30 pixels. If you can still tell what it is, it works.
  • Test on light and dark wallpapers, and in Dark and Tinted modes. A dark icon can vanish on a dark wallpaper unless it has a contrasting edge or highlight (the brass outline does that job here).
  • Avoid text. Words become illegible at small sizes and do not translate. A single very large letter or glyph can work; a word or app name almost never does.
  • Keep the Dark variant's artwork the same shape, just on transparency, and make the Tinted variant a grayscale where light areas are the parts that should take the tint.
AI-Assisted Development: Generating icons with AI tools

Image generators can produce icon concepts quickly, but check the output against the rules above: exactly 1024 × 1024, no alpha in the default icon, square corners (generators love to round them), no tiny text, and a silhouette that survives at 60 pixels. Treat a generated image as a sketch to redraw in vector, not as the final asset.

Part H — Testing appearance, Dynamic Type, Reduce Motion, and VoiceOver

Your code is complete. These steps check that it behaves well for everyone. None of them change code.

Step 39 — Check Light and Dark Mode

  • In the canvas: open ContentView.swift, show the canvas (⌥⌘↩), and switch between the Light and Dark preview tabs.
  • In the running simulator: while the app runs, click the Environment Overrides button in Xcode's debug bar (the small icon with toggles, at the bottom of the editor area when the debug area is shown, ⇧⌘Y). Turn on Appearance and choose Light or Dark. The app switches instantly, because all its colors are adaptive.
  • System-wide: in the simulator, Settings → Developer → Dark Appearance, or Settings → Display & Brightness → Dark; the Simulator menu also has a toggle (Features → Toggle Appearance, ⇧⌘A in recent versions).

Look for anything that did not change: a hard-coded color is the usual cause.

Step 40 — Check Dynamic Type

  • In the canvas: use the canvas's Variants button (bottom bar) and choose Dynamic Type Variants. Xcode renders the preview at every text size side by side. Scroll through them.
  • While running: in Environment Overrides, turn on Text and drag the Dynamic Type slider. The text, the total, and the result circle grow together.
  • System-wide: simulator Settings → Accessibility → Display & Text Size → Larger Text. Turn on Larger Accessibility Sizes for the extreme sizes.

What to look for: text that is cut off with "..." where it should not be, overlapping views, or chips that do not grow. At the largest accessibility sizes, long labels such as "Modifier: +20" may wrap to two lines; that is acceptable and better than truncation. The course author checked a few sizes, not every size, so look for yourself.

Step 41 — Check Reduce Motion

In the simulator, open Settings → Accessibility → Motion and turn on Reduce Motion. Return to Dice Foundry (it may relaunch) and roll. The circle should no longer spin, and the total should change instantly instead of sliding. The roll itself, the history row, and the saved file behave exactly the same, which is the practical proof that animation and calculation are separate. Turn Reduce Motion off afterward.

(Environment Overrides also has an Accessibility section with several switches; whether it includes Reduce Motion depends on your Xcode version. The Settings app route always works.)

Step 42 — Inspect accessibility with the Accessibility Inspector

  1. In Xcode, choose Xcode → Open Developer Tool → Accessibility Inspector.
  2. In the inspector's toolbar, choose your running simulator as the target (the device menu at top left).
  3. Click the target/crosshair button (Inspection Pointer) and hover over elements in the simulator. The inspector shows each element's Label, Traits, Hint, and Value.
  4. Check: a die button shows a label like "6-sided die" and the Selected trait when chosen; the result card is one element with a sentence like "Rolled 3D6 + 2. Total 14. Dice: 4, 2, 6."; each history row is one element; the header has the Header trait; the dice icon in the header does not appear at all.
  5. Try the Audit tab and run an audit. It flags common problems such as small hit areas, low contrast, or missing labels. Read each finding; some are informative rather than errors.

The inspector shows what VoiceOver will read. To hear it, follow Optional Device Lesson D3 on your own iPhone. The course author has not verified VoiceOver output by ear, so treat the labels as a carefully reasoned starting point and adjust the wording if something sounds awkward when you listen.

Step 43 — Check that the haptic toggle is saved

Haptics do not play in the Simulator, so this step checks only the setting. Turn the Haptic feedback toggle off, stop the app with ⌘., press ⌘R to run it again, and confirm the toggle is still off. To feel the haptics on your own iPhone, follow Optional Device Lesson D2.

Expected Results

After Part F the app should look like a finished product. In Dark Mode you should see a charcoal page fading slightly lighter toward the bottom, a serif "Dice Foundry" title with a brass dice icon and the spaced-out studio name beneath it, and a column of dark slate cards, each with a thin brass edge:

Illustrative mockup — not a screenshot (Dark Mode, before the first roll)

  ##   Dice Foundry                          <- serif, bold; brass dice icon
       THE BLACK WELL FOUNDRY                <- small caps, gray

 +--------------------------------------+
 |  [ /\  ]   [ [] ]   [ <> ]          |    <- D6 tile filled brass with
 |   D4        D6*      D8             |       dark text and a gold edge
 |  [ () ]   [ {} ]   [ () ]           |
 |   D10       D12      D20            |
 +--------------------------------------+
 | Number of dice: 1             [- +]  |    <- brass stepper buttons
 |--------------------------------------|
 | Modifier: 0                   [- +]  |
 +--------------------------------------+
 |                 (dice)               |
 |         Tap Roll Dice to begin       |
 +--------------------------------------+
 | History                       Clear  |    <- Clear dimmed (no history)
 | No rolls yet                         |
 +--------------------------------------+
 | ((o)) Haptic feedback          [ON]  |
 +--------------------------------------+
 ......... frosted bar ..................
 |  [========  (dice) Roll Dice  =======] |  <- gold-to-brass gradient button

After rolling 3D6 + 2 (your numbers will differ, because the roll is random):

Illustrative mockup — not a screenshot (Dark Mode, after a roll)

 +--------------------------------------+
 |               3D6 + 2                |    <- brass
 |              .------.                |
 |             /        \               |    <- brass gradient ring,
 |            |    14    |              |       spins once per roll
 |             \        /               |
 |              '------'                |
 |          [ 4 ] [ 2 ] [ 6 ]           |    <- bordered chips
 |       Dice 12, modifier +2           |
 +--------------------------------------+
 | History                       Clear  |
 | [] 3D6 + 2                       14  |
 |    4, 2, 6                   3:42 PM |
 +--------------------------------------+

In Light Mode the same layout appears with a warm off-white background, white cards, deep brass accents, and dark text. The selected die tile is deep brass with white text.

Actual iOS Simulator screenshot — Dice Foundry in Light Mode after one 1D6 roll

Actual iOS Simulator screenshot of Checkpoint 11 in Light Mode after one 1D6 roll. The rolled number on your device will differ.

Actual iOS Simulator screenshot — Dice Foundry in Dark Mode after one 1D6 roll

Actual iOS Simulator screenshot of Checkpoint 11 in Dark Mode after one 1D6 roll, with the gold ring and gold Roll Dice bar. The rolled number on your device will differ.

What you should observe when you interact:

  • Selecting a die: the tapped die turns brass with a gold outline; the previous one returns to neutral.
  • Rolling: the result circle makes one full springy turn, the total's digits slide to the new value, the chips update, and a row appears at the top of History. With Reduce Motion on, there is no spin and the number changes instantly.
  • Scrolling: the cards slide under the frosted Roll Dice bar; the bar never covers the last card when you scroll to the bottom.
  • Haptics toggle: remembered across launches. No vibration in the simulator.
  • Home Screen: the Dice Foundry icon shows a brass D20 on charcoal (Part G).
Note: Screenshots

The mockups above are text approximations; trust your running app and the reference checkpoint over the mockups if they differ in detail.

Reading This Like a Developer

Where execution begins and what runs on a tap

Launch still begins at @main struct DiceFoundryApp, whose WindowGroup creates ContentView. ContentView.body runs, @AppStorage reads hapticsEnabled from UserDefaults (or uses true), and .onAppear calls loadHistory(), which sets history and latestRoll. rollCount stays 0, so ResultView.onChange(of: rollCount) does not fire and .sensoryFeedback does not play. That is why the app opens calmly.

When the user taps Roll Dice:

  1. The Button in rollButton runs its action closure: performRoll().
  2. performRoll() validates the quantity, calls rollDice(count:sides:) (which calls Int.random(in:) once per die), and builds a RollResult. The result is final here.
  3. It assigns latestRoll, increments rollCount, inserts into history, trims to 50, and calls saveHistory(), which writes roll-history.json.
  4. Because @State values changed, SwiftUI re-evaluates ContentView.body. ResultView receives the new roll and rollCount.
  5. Presentation reactions follow: ResultView's .onChange(of: rollCount) calls spin(); the Text total animates via .contentTransition and .animation(value: roll.total); ContentView's .sensoryFeedback checks hapticsEnabled and plays (on a device).

Which variables hold state, and who owns them

Variable Owner Kind Persists? Purpose
selectedDie, quantity, modifier ContentView @State No Roll settings
latestRoll, history ContentView @State Yes, via HistoryStore Roll data
rollCount ContentView @State No Event counter for animation and haptics
hapticsEnabled ContentView @AppStorage Yes, in UserDefaults User preference
rotation ResultView @State No Purely visual spin angle
reduceMotion ResultView @Environment Set by iOS Accessibility setting (read-only)
totalSize, circleSize ResultView @ScaledMetric Set by iOS Sizes that follow Dynamic Type

Business logic vs presentation logic

Business logic (what the app computes): rollDie, rollDice, isValidQuantity, performRoll, RollResult's subtotal/total/notation, and HistoryStore. None of it changed in this chapter except one added line, rollCount += 1, which is a signal for the presentation layer.

Presentation logic (how it looks and feels): everything in Theme, cardStyle(), the component styling, spin(), the content transition, the haptic, and every accessibility modifier. You could delete all of it and the app would compute exactly the same rolls. That separation is what Chapter 12 relies on when it moves the random generation into a testable DiceRoller, and what Chapter 13 relies on when it moves business logic into a view model.

How a color reaches the screen

Brass.colorset/Contents.json   (Any: #8A6424, Dark: #C8A365)
        |  build: asset compiler generates ColorResource.brass
        v
Theme.brass = Color(.brass)
        |  used by views
        v
DieButton .fill(isSelected ? Theme.brass : ...)
        |  at draw time iOS checks the current appearance
        v
Light Mode -> #8A6424      Dark Mode -> #C8A365
Predict Before You Run: Haptics off

The user turns the Haptic feedback toggle off, then rolls twice. What is rollCount after the two rolls (starting from 0 at launch)? Does the circle spin? Does the phone vibrate? Check Prediction Answers.

AI-Assisted Development: Reviewing AI-generated styling code

When an AI agent "makes the app look nicer", review the diff for these patterns: hex colors or Color(red:green:blue:) scattered through views (should come from the asset catalog via Theme); Color("SomeName") string lookups (prefer generated symbols); animation code that calls a random function or decides a result (red flag: calculation must not depend on animation); withAnimation without any Reduce Motion check for large movements; .onAppear used to start animations that then also run at launch; icons and images with no accessibility label or not hidden when decorative; and fixed .frame(width:height:) around text, which breaks with Dynamic Type. A useful instruction to give an agent: "Use only colors from Theme; respect accessibilityReduceMotion; trigger animations from rollCount; never put logic that affects the result inside animation code."

Troubleshooting

"Type 'ColorResource' has no member 'brass'"

error: Type 'ColorResource' has no member 'brass'

The message will be similar to this. Meaning: Swift cannot find a generated symbol named brass. Likely causes: the color set is named differently (for example brass, Brass, with a trailing space, or Brass 1 after a copy-paste); you have not built since creating it; or Generate Swift Asset Symbol Extensions is off. Investigate: check the exact names in the asset list against the table in Step 3, build with ⌘B, and if needed check the build setting mentioned in Step 5. Remember that names are converted to lowerCamelCase: CardBackground becomes .cardBackground, and a trailing "Color" is dropped.

Colors look the same in Light and Dark Mode

Meaning: the color set has only one appearance. Cause: Appearances was left at None, or the Dark well holds the same value as Any. Investigate: select each color set and confirm the Attributes inspector shows Any, Dark with two different swatches. Also confirm the view uses Theme colors rather than a leftover .orange or Color.white.

A color shows as clear or black at runtime, with a console message

No color named 'Brass' found in asset catalog for main bundle

The message will be similar to this. Meaning: code used a string name, Color("..."), that does not match any color set. Investigate: search the project (⇧⌘F) for Color(" and replace string lookups with generated symbols, which the compiler checks.

"Missing argument for parameter 'rollCount' in call"

error: Missing argument for parameter 'rollCount' in call

Meaning: ResultView now has a rollCount property, so every place that creates it must pass one. Cause: Step 18b or 18c was skipped. Investigate: click the error in the Issue navigator (⌘5); it points to either a #Preview in ResultView.swift or the call in ContentView.swift.

The circle does not spin

Causes, in order of likelihood: Reduce Motion is on in the simulator (check Settings → Accessibility → Motion); rollCount += 1 is missing from performRoll(); .onChange(of: rollCount) is attached to the wrong view or missing; spin() sets rotation = 360 instead of adding 360, so only the first roll spins. Investigate: put a breakpoint in spin() and roll. If it is never hit, the trigger is the problem; if it returns early, Reduce Motion is on.

The app spins or buzzes at launch

Cause: an animation or .sensoryFeedback is triggered by latestRoll, history, or .onAppear instead of rollCount. Loading saved history at launch changes those values. Fix: trigger from rollCount, which only performRoll() changes.

"Referencing instance method 'onChange(of:...)' requires that 'RollResult' conform to 'Equatable'"

The message will be similar to this. Meaning: you tried to use latestRoll (a RollResult?) as an onChange or sensoryFeedback trigger. Triggers must be comparable with ==, and RollResult is not Equatable. Fix: use rollCount. (Making RollResult Equatable would compile, but you would then hit the launch problem above.)

The Roll button disappeared

Cause: you completed Step 29 (which deletes the old in-scroll button) but not Step 30 (which adds the pinned one). Fix: add the .safeAreaInset(edge: .bottom) { rollButton ... } block.

The last card is hidden behind the Roll button

Cause: the button was placed with an overlay or ZStack instead of .safeAreaInset, so the scroll view does not know the button is there. Fix: use .safeAreaInset(edge: .bottom) on the ScrollView, as in Step 30.

Die buttons still look gray or bordered

Cause: .buttonStyle(.bordered) and .tint(...) were not removed in Step 13, so the system draws its own style behind or around your design. Fix: replace them with .buttonStyle(.plain).

The new icon does not appear on the Home Screen

Causes: the simulator cached the old icon; the image is in the wrong set or wrong well; the image is not 1024 × 1024. Investigate: select AppIcon and look for a yellow warning triangle on the set (Xcode reports size problems there and in the Issue navigator); confirm the Any Appearance well is filled; delete the app from the simulator and run again (Step 37).

The icon has black corners or a black background

Cause: the default icon has transparency (iOS fills it with black), or the artwork was pre-rounded. Fix: use an opaque, square-cornered PNG in the Any Appearance well; transparency belongs only in the Dark and Tinted images.

No haptic feedback

In the simulator: expected; the simulator cannot play haptics. On a device: check the in-app toggle, and the iPhone's Settings → Sounds & Haptics → System Haptics, which, when off, can suppress app haptics.

Knowledge Check

  1. Why does the project define colors in the asset catalog and reference them through Theme, rather than writing hex values directly in each view? What would you change to make brass slightly warmer across the whole app?
  2. What is the practical difference between Color(.brass) and Color("Brass") when someone renames the color set?
  3. Why is rollCount, rather than latestRoll or roll.total, used to trigger the spin animation and the haptic? Give two separate reasons that rule out latestRoll.
  4. Explain, with reference to performRoll() and spin(), why the animation can never change which numbers are rolled. Why does this matter for accessibility and for testing?
  5. Why does .cardStyle() get applied in ContentView instead of inside ResultView's body, and what does @ScaledMetric add that a fixed CGFloat constant would not?

Independent Challenge

Important: Commit before branching and switching

Before creating a challenge branch, run this chapter's Development Checkpoint on main to commit and tag the guided work. Confirm git status --short prints nothing. After the challenge, commit your practice edits on the challenge branch before switching back to main; uncommitted edits can follow you across branches. If no files changed, no extra commit is needed. The guided checkpoint is already saved, so skip its commit and tag commands when you reach that section again.

Do these on a Git branch so the guided project stays identical to the reference (git switch -c challenge-11; switch back with git switch main before Chapter 12). Hints are in the Chapter 11 Exercises document; full solutions are in the Answer Key.

Challenge: Challenge 1 — A penalty color for negative modifiers

Add a new adaptive color set named Penalty (a muted red) with a light and a dark appearance, expose it as Theme.penalty, and use it in ResultView so the "Dice 12, modifier -3" line is drawn in the penalty color when the modifier is negative, and in .secondary otherwise. Acceptance criteria: the color set has Any and Dark appearances; text in the penalty color has at least 4.5:1 contrast against CardBackground in both modes (state your hex values and contrast ratios); the line keeps its minus sign so the meaning does not depend on color alone; positive modifiers still look as before; the project builds with no warnings.

Challenge: Challenge 2 — Feedback when choosing a die

Make selecting a die feel responsive: play a light .selection haptic when the selected die changes (respecting the Haptic feedback toggle), and animate the die button's change between selected and unselected with a short animation that is turned off when Reduce Motion is on. Acceptance criteria: the selection haptic does not play at launch or on roll; it is controlled by the same hapticsEnabled preference; the selection animation is nil when accessibilityReduceMotion is true; the roll result and roll haptic behave exactly as before; the project builds with no warnings.

Challenge: Challenge 3 — Audit and improve one screen element (no fixed solution)

Use the Accessibility Inspector's Audit on the running app, plus the Dynamic Type variants in the canvas. Pick one real issue it or you find (for example, the wording of a label, a hint you think is missing or unnecessary, or a layout problem at the largest text size), fix it, and write two or three sentences explaining the problem, your change, and how you verified it. Acceptance criteria: a specific before/after description and a verification method; no regression in Light or Dark Mode.

Chapter Completion Checklist

  • Six new color sets exist with exact names and Any/Dark hex values, and AccentColor uses the brass values.
  • Theme/Theme.swift defines the colors, cornerRadius, spacing, two gradients, and cardStyle().
  • DieType has accessibilityName and an exhaustive symbolName switch.
  • Die buttons show shape icons, brass selection with a gold outline, and announce "selected" to VoiceOver.
  • ResultView shows a ringed circle that spins once per roll, digits that slide, and scales with Dynamic Type.
  • The spin and the numeric animation are skipped when Reduce Motion is on.
  • rollCount increases only in performRoll(), after the result is computed, and triggers both the spin and the haptic.
  • The Roll Dice button is pinned at the bottom with .safeAreaInset and never covers the last card.
  • The Haptic feedback toggle works and is remembered across launches.
  • Header, history rows, result card, and Clear button have sensible accessibility labels, traits, or hidden decorations.
  • The app looks right in both Light and Dark previews and in the running simulator.
  • The app icon appears on the simulator Home Screen; Dark and Tinted variants checked on iOS 18+ if available.
  • You can explain why animation must not determine the random result.
  • The project builds with no errors or warnings.

Development Checkpoint

Commit this chapter's work and tag it.

In Xcode: choose Integrate → Commit..., check that the changed files include the new color sets, the AppIcon images, Theme.swift, DieType.swift, the four view files, and ContentView.swift, enter the message Chapter 11: Styling, animation, accessibility, app icon, and click Commit.

In Terminal (from your project folder, the one that contains DiceFoundry.xcodeproj):

git add -A
git commit -m "Chapter 11: Styling, animation, accessibility, app icon"
git tag chapter-11

The asset catalog changes are ordinary files in Git: each color set is a folder with a Contents.json, and the icon PNGs live inside AppIcon.appiconset. git status before committing should list them.

Compare with the reference: open Reference-Checkpoints/Checkpoint-11-Styling-Animation-Accessibility/DiceFoundry/ in Finder. Compare your Swift files with the reference files, for example with:

diff -r path/to/YourProject/DiceFoundry path/to/Reference-Checkpoints/Checkpoint-11-Styling-Animation-Accessibility/DiceFoundry

Expect differences only in the comment header lines Xcode generated (author name, date), in whitespace, and possibly in the copied icon file names inside AppIcon.appiconset. Also compare each *.colorset/Contents.json with the reference: the hex values should match the table in Step 3 (the reference stores them as "red": "0xC8" and so on, and your file may use a slightly different but equivalent format, such as decimal values between 0 and 1). If you prefer, open the reference color set in Xcode and compare the swatches visually.

Prediction Answers

Trace the model (Part C): DieType.d12.accessibilityName is "12-sided die" because the interpolation inserts sides, which is the raw value 12. DieType.d12.symbolName is "hexagon" from the case .d12 branch. DieType.d8.symbolName is "diamond": inside the property, self is .d8, so the switch runs the case .d8 branch and returns immediately.

How far has it turned? (Part E): rotation starts at 0 each time ResultView is created and loading history at launch does not change rollCount, so onChange does not run at launch. Each of the three rolls adds 360, so rotation is 1080 after the third roll (three full turns, number upright). With Reduce Motion on, spin() returns before changing anything, so rotation stays 0.

Haptics off (Reading This Like a Developer): rollCount is 2: performRoll() increments it on every roll regardless of the haptics setting. The circle does spin both times (unless Reduce Motion is on), because the spin depends only on rollCount. The phone does not vibrate, because .sensoryFeedback's condition closure returns hapticsEnabled, which is false. The trigger fired; the condition vetoed the feedback.