Chapter 10 Exercises — Reusable Components and Code Organization
Do these exercises on a separate Git branch so your guided project stays identical to the reference checkpoint:
First commit and tag the guided work using the workbook's Development Checkpoint. Confirm git status --short prints nothing, then create the branch:
git switch -c challenge-10
When you are finished, commit your work on the branch, even if it is unfinished (or run git stash -u to set it aside), and only then return to the main line. Uncommitted edits and new untracked files follow you across git switch, and because Xcode folders mirror the disk, a leftover file such as a new view would be compiled into your main project. Then switch back:
Uncommitted edits can follow you across branches. Save them before switching; if nothing changed, skip add and commit. The status command should print nothing:
git add -A
git commit -m "Challenge 10: Save practice work"
git status --short
git switch main
Solutions are in the Chapter 10 Answers document. Use the hints one at a time.
Challenge 1 — A reusable RollButton
Goal: extract the Roll Dice button from ContentView into its own component, Views/RollButton.swift.
Requirements:
RollButtonhas no@Stateand no@Binding.- It receives what should happen on a tap through a closure property.
- It keeps the same title ("Roll Dice") and modifiers:
.font(.title2),.buttonStyle(.borderedProminent),.controlSize(.large),.tint(.orange). - It has a
#Preview. ContentViewuses it, tapping it still callsperformRoll(), andperformRoll()staysprivate.
Acceptance criteria:
- The project builds with no errors or warnings.
- The app behaves exactly as before: run the Chapter 10 regression checklist (Step 1 table).
- The
RollButtonpreview shows an orange "Roll Dice" button.
Hint 1
Look at DieButton. It is the same pattern with fewer inputs: a view whose only job is to look like a button and report a tap. Which of DieButton's three properties does RollButton need?
Hint 2
The property is let action: () -> Void. Button has an initializer that takes a title and an action: Button("Some title", action: someClosure). The modifiers that were on the button in ContentView move into RollButton's body, attached to that Button.
Hint 3
In ContentView.body, replace the Button("Roll Dice") { ... } and its four modifiers with RollButton { performRoll() }. The trailing closure becomes the action property. Because the closure is written inside ContentView, it can call the private performRoll(); RollButton never sees that function. In the preview, RollButton {} passes an empty closure.
Challenge 2 — A ValueChip component
Goal: extract the individual die value display in ResultView into Views/ValueChip.swift.
Requirements:
- One input property holding the value to show.
- The chip looks exactly like the current one:
.title3, semibold, 44 by 44 points, light orange background, rounded corners with radius 8. - A
#Previewshowing several chips side by side. ResultViewusesValueChipinside itsForEach.
Acceptance criteria:
- Builds with no errors or warnings.
- Rolls look identical in the app.
- Both
ResultViewpreviews ("With a roll" and "Empty") still render.
Hint 1
Does a chip need to change anything, or only display? That tells you whether its input is a let or a @Binding. What type is one die value?
Hint 2
Move the Text("\(roll.values[index])") and its five modifiers into the new view's body. Inside ValueChip there is no roll or index, only your input property, so the Text shows that property instead.
Hint 3
The struct has let value: Int and a body that returns Text("\(value)") with the five modifiers. In ResultView, the ForEach body becomes a single line: create a ValueChip, passing roll.values[index] as its value. A preview can put three chips in an HStack.
Extra Practice
Exercise 10.1 — One-way or two-way?
For each proposed component, decide whether its input should be a plain let property, a @Binding, or a closure, and explain why: (a) a TotalBadge that shows a roll's total; (b) a QuantityPicker with its own + and - buttons that changes how many dice to roll; (c) a ClearHistoryButton that should empty the history; (d) a DieIcon that shows a die type's name.
Exercise 10.2 — Spot the bug
This version of DiePicker builds and the previews look fine. In the running app, tapping a die highlights it, but rolls always use the die that was selected when the app launched. Explain why.
struct DiePicker: View {
@State var selection: DieType
var body: some View {
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]) {
ForEach(DieType.allCases) { dieType in
DieButton(dieType: dieType, isSelected: dieType == selection) {
selection = dieType
}
}
}
}
}
// In ContentView:
DiePicker(selection: selectedDie)
Exercise 10.3 — Predict the compiler's response
A colleague marks every property of HistoryRow private for "safety":
struct HistoryRow: View {
private let roll: RollResult
...
}
What happens when ContentView builds HistoryRow(roll: roll)? Why does the same thing not happen for DiePicker's private let columns?
Exercise 10.4 — Small modification
Add a third preview to ResultView.swift named "No modifier" that shows a 2D8 roll with values 3 and 5 and modifier 0. Before you look at the canvas, predict which lines of text appear and which do not.
Exercise 10.5 — Should it be a component?
Someone proposes extracting the title HStack (the dice icon and "Dice Foundry") into TitleView, and also extracting Divider() into HistoryDivider. Argue for or against each.