Dice Foundry Solutions and Answer Key

Chapter 10 Answers — Reusable Components and Code Organization

Knowledge Check Answers

1. Refactoring. Refactoring changes the structure of code without changing its behavior. You check it by recording the app's behavior before the change (a manual test script such as the Step 1 table), changing one thing at a time and building after each step, and running the same script afterward. Results must match. In Chapter 12, unit tests automate part of this for logic; for views, a manual checklist plus previews is the practical tool.

2. @Binding versus let. DiePicker must change the selected die, which ContentView owns, so it needs a two-way connection: a binding. ResultView only displays the latest roll and never changes it, so a plain let (one-way data) is enough and makes the intent clear. If DiePicker used @State, it would own a separate copy of the selection. Tapping would change the picker's copy (and its highlight), but ContentView.selectedDie would never change, so rolls would use the wrong die: two sources of truth that disagree.

3. $. $selectedDie produces a Binding<DieType>: a two-way connection to the @State storage rather than a copy of its current value. Stepper needs a binding because it changes a number it does not own. RollOptionsView needs bindings for the same reason, and passes them on to its steppers with $quantity and $modifier (on a @Binding property, $ gives you the binding itself).

4. Why formatModifier moved. Both RollOptionsView and ResultView need the same formatting. Copying the function would create two copies of one rule; any future change would have to be made twice, and the copies would eventually drift apart (duplication is a code smell). Moving it to one place keeps a single source of truth for the rule. RollResult is the natural home because it is knowledge about roll data, and static lets callers format any number, including the stepper's live value before any roll exists.

5. Access control. The default is internal: visible anywhere in the same module (the app target). ContentView's functions and store are implementation details only ContentView uses, so private guarantees no other file depends on them and tells readers they only need to look in this file. DieButton's dieType, isSelected and action are its inputs: the parent supplies them through the memberwise initializer. Making them private (with no default value) would make that initializer private as well, and the parent could not create the button.

Challenge Solutions

Challenge 1 — A reusable RollButton

File: new file Views/RollButton.swift · Action: Create file

Example — not part of the Dice Foundry project
import SwiftUI

struct RollButton: View {
    let action: () -> Void

    var body: some View {
        Button("Roll Dice", action: action)
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)
    }
}

#Preview {
    RollButton {}
}

File: ContentView.swift · Where: inside body, the Roll Dice button and its four modifiers, between ResultView(roll: latestRoll) and historySection · Action: Replace

Example — not part of the Dice Foundry project
                RollButton {
                    performRoll()
                }

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Solution folder: challenge-solutions/ch10-roll-button/.

Why it works. RollButton's memberwise initializer is RollButton(action:). Because action is its last (and only) parameter and is a closure, ContentView can pass it as a trailing closure. The closure is written in ContentView, so it can call the private performRoll(); RollButton simply stores the closure and hands it to Button(_:action:), the initializer that takes a title string and an action. The modifiers are the same ones that were in ContentView, in the same order, so the button looks identical. No state moved, so behavior is unchanged.

Alternatives. You could keep the trailing-closure form inside RollButton (Button("Roll Dice") { action() }), which calls the stored closure from a new closure; it works but adds a layer. You could add a let title: String input to make the button reusable for other labels, but nothing in the app needs that yet, so it would be speculative. Some developers would leave the button inline: it is used once and is only a few lines. Extracting it is reasonable if you expect to restyle it (Chapter 11 does restyle it), but it is not required.

Challenge 2 — A ValueChip component

File: new file Views/ValueChip.swift · Action: Create file

Example — not part of the Dice Foundry project
import SwiftUI

struct ValueChip: View {
    let value: Int

    var body: some View {
        Text("\(value)")
            .font(.title3)
            .fontWeight(.semibold)
            .frame(width: 44, height: 44)
            .background(Color.orange.opacity(0.2))
            .clipShape(RoundedRectangle(cornerRadius: 8))
    }
}

#Preview {
    HStack {
        ValueChip(value: 4)
        ValueChip(value: 2)
        ValueChip(value: 6)
    }
}

File: Views/ResultView.swift · Where: inside the ForEach(roll.values.indices, id: \.self) { index in ... } · Action: Replace the Text and its five modifiers

Example — not part of the Dice Foundry project
                    ForEach(roll.values.indices, id: \.self) { index in
                        ValueChip(value: roll.values[index])
                    }

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Solution folder: challenge-solutions/ch10-value-chip/.

Why it works. A chip only displays a number, so its input is a plain let value: Int, the simplest one-way data flow. ResultView still decides which values to show and in what grid; ValueChip decides how one value looks. The modifiers are unchanged, so the chips look identical, and the ResultView previews still render because ResultView's own inputs did not change.

Alternatives. You could pass the whole RollResult and an index, but that couples the chip to the roll type for no benefit. If you later want to restyle the chips (Chapter 11 restyles the whole app), the change happens in one place.

Extra Practice Answers

10.1 — One-way or two-way? (a) TotalBadge: let total: Int (or let roll: RollResult); it only displays. (b) QuantityPicker: @Binding var quantity: Int; it changes a value owned by the parent, like RollOptionsView. (c) ClearHistoryButton: a closure, let action: () -> Void; the button reports an event and the parent, which owns the history and the save logic, decides what clearing means. Passing a binding to the whole history would also let it empty the array, but then it would bypass clearHistory() and the file would not be saved. (d) DieIcon: let dieType: DieType; display only.

10.2 — Spot the bug. DiePicker declares @State var selection, so it owns its own copy, initialized once from the value ContentView passed in (selectedDie, with no $). Tapping changes the picker's private copy, so its highlight updates, but ContentView.selectedDie never changes, and performRoll() reads ContentView.selectedDie. Fix: @Binding var selection: DieType in DiePicker and DiePicker(selection: $selectedDie) in ContentView. (The inline columns array is not a bug, just less readable than a named columns property.)

10.3 — Predict the compiler's response. Because roll is a stored property with no default value, it must be set by the initializer, and Swift gives the memberwise initializer the most restrictive access level of the properties it sets. The initializer becomes private, so ContentView gets an error similar to "'HistoryRow' initializer is inaccessible due to 'private' protection level". DiePicker's private let columns has a default value, so it is not a parameter of the memberwise initializer and does not affect its access level.

10.4 — Small modification.

Example — not part of the Dice Foundry project
#Preview("No modifier") {
    ResultView(roll: RollResult(dieType: .d8, values: [3, 5], modifier: 0))
}

Visible: the notation "2D8" (no "+ 0"), the total 8 in the circle, and chips 3 and 5. Not visible: the "Dice 8, modifier ..." line, because roll.modifier != 0 is false, and the "Tap Roll Dice to begin" prompt, because roll is not nil.

10.5 — Should it be a component? TitleView: defensible but optional. It is used once and is simple; extracting it shortens body slightly and could be justified if the title becomes more elaborate (Chapter 11 styles it). A private var computed property would be a lighter choice. HistoryDivider: against. A wrapper around a single built-in view adds a type, a file and a name to learn without adding meaning or reuse. This is the "abstraction to demonstrate architecture" the chapter warns about.