Chapter 10 — Reusable Components and Code Organization
ContentView.swift has grown to more than 200 lines. Its body alone describes the title, the die grid, both steppers, the result display, the Roll button and the whole history list, and the file also holds the dice logic and the persistence calls. It works, but finding anything takes scrolling, and every change risks disturbing something unrelated. In this chapter you refactor: you change how the code is organized without changing what the app does. You split the screen into small, named views (DieButton, DiePicker, RollOptionsView, ResultView, HistoryRow), learn how a parent view passes data down to its children and how a child can change the parent's state through a @Binding, sort the files into folders, and mark implementation details private. You finish by running the same manual test before and after, to prove the app behaves exactly as it did. These are the skills that let you read a large SwiftUI project, including one an AI assistant generated, and know where to look.
Learning Objectives
By the end of this chapter you will be able to:
- Explain what refactoring is and why it becomes valuable as an app grows.
- Break a large view into smaller child views, each in its own file.
- Pass data from a parent view into a child view through plain properties (one-way).
- Use
@Bindingso a child view can read and change state owned by its parent (two-way), and explain$fully. - Explain the idea of a single source of truth and identify the owner of each piece of state in Dice Foundry.
- Pass an action into a child view as a closure property (
let action: () -> Void). - Write previews for child views using sample values and
.constant(...)bindings. - Use the
if let rollshorthand to unwrap an optional. - Extract part of a
bodyinto a computed view property. - Move duplicated logic to one shared place (
RollResult.formatModifier) and explain why duplication is a code smell. - Organize files into
Models,PersistenceandViewsfolders, and confirm target membership. - Apply naming conventions for types, files, properties and functions.
- Use access control: the default
internal,private, and the existence offileprivateandpublic. - Verify that a refactoring did not change behavior with a before/after regression checklist.
Concept Explanation
What refactoring is, and why now
Refactoring means changing the structure of code without changing its behavior. The user should not be able to tell that anything happened. The benefit is for the people (and tools) that read and change the code: smaller pieces with clear names are easier to understand, test and modify.
Early in a project, one file is fine. You did not need components in Chapter 3, when the screen was a title and a button. Splitting code before you understand it produces abstractions that fit badly. Now the shape of the app is clear, and you can see natural seams: the die picker, the roll options, the result display, a history row. Refactoring at this point is cutting along lines that already exist.
You have probably seen a single 2,000-line Ansible playbook or Terraform file that "works", and the relief of splitting it into roles or modules with clear inputs. Nothing about the deployed infrastructure changes; what changes is how quickly you can find and safely edit things. SwiftUI components are modules for the user interface: each has inputs (properties) and produces a piece of the screen.
There is a matching danger: splitting too much. A view with three lines does not need its own file "for architecture". A good component has a clear job, a name that describes that job, and ideally either reuse (DieButton appears six times) or a meaningful boundary (ResultView is "everything about showing a roll"). This chapter creates five components and one computed property, and stops.
Views are structs with properties
You already know that a SwiftUI view is a struct that conforms to View and has a body. You also know from Chapter 8 that a struct gets a memberwise initializer from its stored properties. Put those together and you have the whole mechanism for passing data into a child view:
struct Greeting: View {
let name: String // input
var body: some View {
Text("Hello, \(name)")
}
}
// In a parent's body:
Greeting(name: "Ada") // memberwise initializer supplies the input
Greeting cannot change name; it only displays it. The parent decides the value. When the parent's state changes and the parent's body runs again, it creates a new Greeting with the new value, and SwiftUI updates the screen. Data flows down, one way.
ResultView and HistoryRow work exactly like this: let roll: RollResult? and let roll: RollResult.
Parent, child, and the single source of truth
When ContentView's body contains DiePicker(...), ContentView is the parent and DiePicker is a child. DiePicker in turn contains six DieButton children. This forms a tree of views, just like the view hierarchy you met in Chapter 3, but now some branches are your own named types.
Which view should own each piece of state? The rule is: each piece of data has exactly one owner, the single source of truth. Everyone else reads it or is given a way to change it; nobody keeps a separate copy that could drift out of sync.
| Data | Owner | Who reads it | Who changes it |
|---|---|---|---|
selectedDie |
ContentView (@State) |
DiePicker, performRoll() |
DiePicker, via a binding |
quantity, modifier |
ContentView (@State) |
RollOptionsView, performRoll() |
RollOptionsView, via bindings |
latestRoll |
ContentView (@State) |
ResultView |
performRoll(), loadHistory() |
history |
ContentView (@State) |
historySection, HistoryRow |
performRoll(), clearHistory(), loadHistory() |
All state stays in ContentView because performRoll() needs the selected die, quantity and modifier together, and the history and latest roll are produced there. Children receive what they need.
This is the DNS or CMDB principle: one authoritative source, everything else derived from it. If two servers each held their own copy of a configuration value and you updated only one, you would get split-brain behavior. Two @State copies of selectedDie (one in ContentView, one in DiePicker) produce exactly that bug: the picker highlights D20 while the roll uses D6.
Two-way data flow: @Binding
DiePicker must do more than display the selection: tapping a button must change it. But the selection belongs to ContentView. If DiePicker declared its own @State var selection, it would own a separate copy, and ContentView would never see the change.
A binding solves this. A Binding<DieType> is not a value; it is a two-way connection to a value stored somewhere else. Reading through the binding gets the owner's current value; writing through it changes the owner's value. In a child view you declare one with @Binding:
struct DiePicker: View {
@Binding var selection: DieType // a connection to someone else's DieType
...
}
The parent creates the binding with $:
DiePicker(selection: $selectedDie) // pass a connection, not a copy
Now you can understand $ fully. You first used it in Chapter 6 with Stepper(..., value: $quantity, ...), with a promise to explain it later. For any @State (or @Binding) property:
| You write | You get | Type (for selectedDie) |
|---|---|---|
selectedDie |
The current value | DieType |
$selectedDie |
A binding to the value | Binding<DieType> |
Stepper takes a Binding<Int> for exactly the reason DiePicker takes a Binding<DieType>: it needs to change a value it does not own. You are now building your own controls the way Apple builds theirs.
Inside the child, you use the property name normally: selection reads the value, selection = dieType writes it (which writes the parent's @State, which triggers a re-render), and $selection would pass the binding further down to another child, which is exactly what RollOptionsView does with $quantity when it hands it to Stepper.
Think of @State as the record held by the owner and @Binding as a mounted volume or a symbolic link: the child reads and writes through it, but the bytes live in one place. Passing selectedDie (no $) is like handing someone a printed copy; passing $selectedDie is like handing them write access to the original.
The same hierarchy in text:
ContentView (owns all @State)
|-- DiePicker <==== $selectedDie (@Binding, two-way)
| |-- DieButton x 6 <--- dieType, isSelected (plain properties, one-way)
| ---> action closure (child calls back up)
|-- RollOptionsView <==== $quantity, $modifier (@Binding, two-way)
|-- ResultView <---- latestRoll (plain property, one-way)
|-- Button("Roll Dice")
'-- historySection (computed property inside ContentView)
'-- HistoryRow x n <--- roll (plain property, one-way)
Passing actions down: closure properties
DieButton is a small, reusable button. It should not know about selectedDie or ContentView at all; it only knows which die it shows, whether it is highlighted, and that something should happen when it is tapped. The "something" is supplied by the parent as a closure.
You have used closures since Chapter 4: a button's action is a closure. A closure can also be stored in a property, and its type is written with an arrow:
let action: () -> Void
Read () -> Void as "a function that takes no inputs and returns nothing". Void means "no value". DieButton stores that closure and gives it to its Button. When the user taps, the button calls the closure, which runs the parent's code. This is how a child reports an event up to its parent without knowing anything about the parent.
A closure property is a callback: the parent registers "call this when you're tapped", the same way you register a webhook URL or an ExecStartPost= command. The component fires the event; the owner decides what it means.
Access control
Every declaration in Swift has an access level, which controls which other code can see it:
| Level | Visible to | When to use |
|---|---|---|
private |
Only the enclosing declaration (and its extensions in the same file) | Implementation details: helper functions, layout constants, the store |
fileprivate |
Anything in the same file | Rare; sharing a helper between two types in one file |
internal (the default) |
Anything in the same module (your app target) | Things other files in the app need |
public / open |
Other modules | Frameworks and Swift packages; not needed in an app target |
If you write nothing, the level is internal. That is why ContentView could call RollResult's properties from another file all along.
You met private in Chapter 4 on @State properties. In this chapter, you mark everything in ContentView that only ContentView uses as private: the store, historySection, and all the functions. The compiler then guarantees no other file depends on them, so you can change them freely. It also documents intent: when you see private, you know you only have to look in this file.
Child views' input properties (let roll, @Binding var selection, let action) are left internal, because the parent must be able to set them through the initializer. Their layout constants (private let columns) are private.
AI assistants are inconsistent with access control: some generate everything public (often copied from library code), others mark nothing. In an app target, public adds nothing and suggests the code was written for a framework. A useful review question: "Is anything here marked public or open without a reason?" A useful instruction: "Mark helper functions and stored properties that are only used inside the view private."
Naming and file organization
Swift convention, which this course follows:
| Thing | Convention | Examples |
|---|---|---|
| Types (struct, enum, class) | UpperCamelCase, a noun | DieButton, HistoryStore, RollResult |
| Properties, variables, functions | lowerCamelCase | selectedDie, historySection, performRoll() |
| Booleans | Read as a statement | isSelected, isEmpty, isValidQuantity(_:) |
| Functions that do something | Start with a verb | loadHistory(), clearHistory() |
| View components | Describe what they show; View suffix only when the name would otherwise be vague |
DiePicker, ResultView, RollOptionsView, HistoryRow |
| Files | One main type per file, file named after the type | DieButton.swift |
Folders group files by responsibility:
DiceFoundry/
DiceFoundryApp.swift
ContentView.swift
Models/ what the app's data is DieType, RollResult
Persistence/ how data is stored HistoryStore
Views/ reusable pieces of screen DieButton, DiePicker, RollOptionsView,
ResultView, HistoryRow
ContentView.swift and the app file stay at the top level because they are the entry points. Later chapters add Theme/, Logic/ and ViewModels/.
Folders in the Project navigator can work in one of two ways, depending on how Xcode created your project. Some folders mirror real folders on disk: creating one in Xcode creates it in Finder, and moving a file between them moves it on disk. Other folders exist only inside Xcode. Check your project: after you create a folder, look for it in Finder. Either way, the steps in this chapter work. The Swift compiler does not care about folders: every .swift file in the target is compiled together, so moving a file never requires an import or a path change.
Duplication is a smell
Both the modifier stepper and the result display need to show a modifier as +2, 0 or -4. Today that logic lives in ContentView.formattedModifier(_:). After you split the views, both RollOptionsView and ResultView need it. The lazy option is to copy the function into both files. Then a future change ("show ±0") must be made twice, and the day someone forgets, the two places disagree.
Repeated logic is called a code smell: not necessarily a bug, but a sign that a bug is likely later. The fix is to give the logic one home. Formatting a modifier is knowledge about a roll's data, so it moves to RollResult as a static function: RollResult.formatModifier(2) returns "+2". It is static because it does not need a particular roll; it formats any number (the stepper's live value has no roll yet). You learned static let in Chapter 9; static func is the same idea for a function.
When you ask an assistant to "add a modifier display to the result view", it will often write a fresh formatting function inside that view rather than finding the existing one. Over a few prompts you end up with three slightly different versions. When you read generated code, search the project for similar function names (format, formatted, display) before accepting a new one, and tell the assistant where shared logic lives: "Use RollResult.formatModifier for modifier text."
Refactoring safely
Refactoring has one rule: behavior must not change. To make that verifiable:
- Write down what the app does before you start (a manual test script).
- Change one thing at a time and build after each change. If something breaks, you know which change did it.
- Run the same test script at the end and compare.
In Chapter 12 you will automate some of this with unit tests. For views, a careful manual checklist is the practical tool.
Syntax Breakdown
A binding property
@Binding var selection: DieType
| Token | Meaning |
|---|---|
@Binding |
A property wrapper: this property does not store its own value; it reads and writes a value owned elsewhere. |
var |
Must be var, because writing through it changes the value. |
selection |
The name used inside the child. Reading selection gives a DieType. |
: DieType |
The type of the value at the other end of the binding. |
The memberwise initializer for a @Binding var selection: DieType property takes a parameter of type Binding<DieType>: DiePicker(selection: Binding<DieType>).
Passing a binding
DiePicker(selection: $selectedDie)
| Token | Meaning |
|---|---|
DiePicker(...) |
Creates the child view with its memberwise initializer. |
selection: |
The argument label, from the property name. |
$selectedDie |
The binding to ContentView's @State property, of type Binding<DieType>. |
A constant binding for previews
DiePicker(selection: .constant(.d20))
| Token | Meaning |
|---|---|
.constant(...) |
Short for Binding.constant(...): a binding to a fixed value that ignores writes. |
.d20 |
The value the binding always returns. |
Use it in previews, where there is no parent @State to bind to. Taps in the preview will not change the highlight, because the constant binding discards writes.
A closure property
let action: () -> Void
| Token | Meaning |
|---|---|
let action |
A constant stored property named action. |
: |
Type annotation follows. |
() |
The closure takes no parameters. |
-> |
"returns". |
Void |
Nothing. The closure is run for its effect, not for a value. |
Button(action: action) { ... } passes that stored closure as the button's action (the action: initializer of Button), with the label in the trailing closure. Notice there are no parentheses after the second action: you pass the closure itself, not the result of calling it.
A trailing closure for a closure property
DieButton(dieType: dieType, isSelected: dieType == selection) {
selection = dieType
}
DieButton's memberwise initializer is DieButton(dieType:isSelected:action:). Because action is the last parameter and is a closure, you can write it as a trailing closure after the parentheses, exactly as with Button. In the preview, DieButton(dieType: .d6, isSelected: true) {} passes an empty closure that does nothing.
The if let shorthand
if let roll {
| Form | Meaning |
|---|---|
if let roll = roll { |
The long form from Chapter 2: unwrap the optional roll into a new non-optional constant also named roll. |
if let roll { |
Shorthand for the same thing (Swift 5.7+). Use it when the unwrapped name is the same as the optional's name. |
Inside the braces, roll is a RollResult, not a RollResult?.
A computed view property
private var historySection: some View {
| Token | Meaning |
|---|---|
private |
Only ContentView uses it. |
var historySection |
A computed property (Chapter 5): no stored value; its body runs each time it is read. |
: some View |
Returns some specific view type, like body. |
body then simply says historySection. This is a lighter alternative to a separate component when the piece is used once and needs lots of the parent's state and functions (here, history and clearHistory()).
A static function
static func formatModifier(_ value: Int) -> String { and the call RollResult.formatModifier(modifier).
| Token | Meaning |
|---|---|
static func |
A function that belongs to the type, called through the type name. |
formatModifier |
Verb phrase: what it does. |
(_ value: Int) |
One unlabeled Int parameter, so the call reads formatModifier(2). |
-> String |
Returns the formatted text. |
Named previews
#Preview("With a roll") { ... } gives a preview a name. A file can contain several #Preview blocks; the canvas shows each as a separate tab, labeled with its name. ResultView.swift uses two, one for each state the view can be in.
Guided Implementation
Start from your completed Chapter 9 project. The order below keeps the project building after every step. Build (⌘B) whenever you are told to; if a build fails, fix it before moving on, so you always know which step caused a problem.
Step 1 — Record the "before" behavior
Before changing any code, run the app (⌘R) and work through this checklist. Write down what you see, or keep it in mind as the reference behavior.
| # | Action | Expected (Chapter 9 behavior) |
|---|---|---|
| 1 | Fresh state: tap Clear (if enabled), Stop, Run | "Tap Roll Dice to begin", "No rolls yet", Clear disabled |
| 2 | Tap D20 | D20 is orange; others gray |
| 3 | Tap + on Number of dice twice | "Number of dice: 3" |
| 4 | Tap + on Modifier twice, then - four times | "Modifier: +2", then "Modifier: -2" |
| 5 | Tap Roll Dice | Notation "3D20 - 2", big total, three value chips, "Dice N, modifier -2", a history row |
| 6 | Set modifier back to 0 and roll | Notation "3D20", no "Dice N, modifier" line |
| 7 | Stop and Run | History restored, result area shows the newest roll, controls reset to D6, 1, 0 |
| 8 | Tap Clear | "No rolls yet", Clear disabled |
| 9 | Number of dice: press - at 1, + at 10 | Stepper stops at 1 and at 10 |
| 10 | Modifier: past -20 and +20 | Stepper stops at -20 and +20 |
Commit your Chapter 9 work if you have not already (see the Chapter 9 Development Checkpoint). A clean commit lets you compare or roll back if the refactoring goes wrong.
Step 2 — Create folders and move the model and persistence files
File: Project navigator · Where: inside the yellow DiceFoundry folder · Action: Move
- In the Project navigator, right-click the
DiceFoundryfolder that containsContentView.swiftand choose New Folder. Name itModels. - Repeat to create
PersistenceandViews. - Drag
DieType.swiftandRollResult.swiftintoModels. - Drag
HistoryStore.swiftintoPersistence. - Leave
DiceFoundryApp.swift,ContentView.swiftandAssets.xcassetswhere they are.Viewsstays empty for now. - Select
DieType.swiftand open the File inspector (⌥⌘1). Under Target Membership, confirm DiceFoundry is checked. Check the other two moved files the same way.
Your project may use either kind of folder. If New Folder creates a folder that appears in Finder, it mirrors disk. If your context menu offers only New Group, the folder exists only in Xcode; that is fine for this course. If you want the disk layout to match what you see, choose New Group with Folder where it is offered. Either way, the compiler builds every .swift file that belongs to the target, regardless of folder.
What it does: organizes files by responsibility. No code changes.
The moved Models/DieType.swift is unchanged; this is the complete file at the end of this step.
//
// DieType.swift
// DiceFoundry
//
import Foundation
enum DieType: Int, CaseIterable, Identifiable, Codable {
case d4 = 4
case d6 = 6
case d8 = 8
case d10 = 10
case d12 = 12
case d20 = 20
var id: Int {
rawValue
}
var sides: Int {
rawValue
}
var name: String {
"D\(rawValue)"
}
}
The moved Persistence/HistoryStore.swift is also unchanged; this is the complete file at the end of this step.
//
// HistoryStore.swift
// DiceFoundry
//
import Foundation
struct HistoryStore {
static let maximumCount = 50
let fileURL: URL
init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
self.fileURL = fileURL
}
func load() throws -> [RollResult] {
if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
return []
}
let data = try Data(contentsOf: fileURL)
let history = try JSONDecoder().decode([RollResult].self, from: data)
return history
}
func save(_ history: [RollResult]) throws {
let data = try JSONEncoder().encode(history)
try data.write(to: fileURL, options: .atomic)
}
}
What next: build (⌘B) and run. The app should behave exactly as before. If the build fails with "Cannot find 'RollResult' in scope" or similar, a moved file has lost its target membership; recheck step 6.
Step 3 — Give RollResult a shared formatModifier
File: Models/RollResult.swift · Where: inside struct RollResult, after the closing brace of valuesDescription, before the struct's final } · Action: Add
static func formatModifier(_ value: Int) -> String {
switch value {
case 0:
return "0"
case 1...:
return "+\(value)"
default:
return "\(value)"
}
}
What it does: the same switch you wrote in Chapter 7, now owned by the model type, callable as RollResult.formatModifier(...) from any file.
Why static: formatting a number does not need a specific roll. The modifier stepper calls it with the live modifier before any roll exists.
Why add it now, before deleting the old one: ContentView still calls formattedModifier(_:). Adding the new function first means the project keeps building. You delete the old function in Step 9, once nothing uses it.
What next: build. No visible change.
This is the complete Models/RollResult.swift at the end of this step, with formatModifier added.
//
// RollResult.swift
// DiceFoundry
//
import Foundation
struct RollResult: Identifiable, Codable {
let id: UUID
let dieType: DieType
let values: [Int]
let modifier: Int
let date: Date
init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
self.id = id
self.dieType = dieType
self.values = values
self.modifier = modifier
self.date = date
}
var subtotal: Int {
values.reduce(0, +)
}
var total: Int {
subtotal + modifier
}
var notation: String {
let dice = "\(values.count)\(dieType.name)"
if modifier > 0 {
return "\(dice) + \(modifier)"
} else if modifier < 0 {
return "\(dice) - \(abs(modifier))"
} else {
return dice
}
}
var valuesDescription: String {
values.map { String($0) }.joined(separator: ", ")
}
static func formatModifier(_ value: Int) -> String {
switch value {
case 0:
return "0"
case 1...:
return "+\(value)"
default:
return "\(value)"
}
}
}
Step 4 — Create DieButton
File: new file DieButton.swift · Where: right-click the Views folder → New File from Template... → iOS → SwiftUI View → name it DieButton (DiceFoundry target checked) · Action: Create file
Choosing the SwiftUI View template creates a file with import SwiftUI, a placeholder struct and a #Preview. Replace everything after the comment header with the following. First the struct:
import SwiftUI
struct DieButton: View {
let dieType: DieType
let isSelected: Bool
let action: () -> Void
var body: some View {
Button(action: action) {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(isSelected ? .orange : .gray)
}
}
Then the preview at the bottom of the file:
#Preview {
HStack {
DieButton(dieType: .d6, isSelected: true) {}
DieButton(dieType: .d20, isSelected: false) {}
}
.padding()
}
What it does: one die button. It shows the die's name, is orange when isSelected is true and gray otherwise, and calls action when tapped.
Why it is written this way:
- Compare it with the code inside the Chapter 9
ForEach: theTextand modifiers are identical, so it looks identical. - The Chapter 9 version computed the color with
dieType == selectedDie.DieButtondoes not know what "selected" means in the app; it receives the answer asisSelected: Bool. That makes it reusable anywhere you need a die button in a highlighted or normal state. - The Chapter 9 version set
selectedDie = dieTypedirectly in the button.DieButtoncannot do that (it has no access toContentView's state), so it receives the behavior asaction. - All three properties are
let: aDieButtonnever changes its inputs. When the parent's state changes, SwiftUI creates newDieButtonvalues.
What next: open the canvas (⌥⌘↩) and resume the preview if needed (⌥⌘P). You should see an orange D6 button and a gray D20 button side by side. Tapping them in the preview does nothing, because the closures are empty. Build: the app is unchanged, because nothing uses DieButton yet.
Step 5 — Create DiePicker
File: new file DiePicker.swift · Where: Views folder, using the SwiftUI View template · Action: Create file
import SwiftUI
struct DiePicker: View {
@Binding var selection: DieType
private let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(DieType.allCases) { dieType in
DieButton(dieType: dieType, isSelected: dieType == selection) {
selection = dieType
}
}
}
}
}
And its preview:
#Preview {
DiePicker(selection: .constant(.d20))
.padding()
}
What it does: the grid of six die buttons. For each dieType, it creates a DieButton, computes isSelected by comparing with selection, and passes a closure that writes the tapped die into selection.
Why it is written this way:
selectionis a@BindingbecauseDiePickermust change a value thatContentViewowns. Writingselection = dieTypewrites through the binding toContentView's@State var selectedDie.columnsmoved here fromContentViewbecause only the grid uses it. It isprivatebecause nothing outsideDiePickerneeds it, and because it has a default value it does not appear in the memberwise initializer. The initializer is simplyDiePicker(selection:).- The name
selection(rather thanselectedDie) describes the picker's role, which is the convention for selection controls in SwiftUI. - The preview has no parent state, so it passes
.constant(.d20). D20 is highlighted. Tapping another die in the preview does not move the highlight, because constant bindings ignore writes. That is expected.
What next: check the preview: a 3-by-2 grid with D20 orange. Build. The app is still unchanged.
Step 6 — Use DiePicker in ContentView
File: ContentView.swift · Where: inside body, the whole LazyVGrid(columns: columns, spacing: 12) { ... } block after the title HStack · Action: Replace
Before (delete all of this):
LazyVGrid(columns: columns, spacing: 12) {
ForEach(DieType.allCases) { dieType in
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(dieType == selectedDie ? .orange : .gray)
}
}
After:
DiePicker(selection: $selectedDie)
Then delete the now-unused columns property near the top of ContentView:
File: ContentView.swift · Where: the let columns = [ ... ] property, below let store = HistoryStore() · Action: Delete
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
Delete it only after replacing the grid; if you delete it first, the old grid code would fail to compile with "Cannot find 'columns' in scope".
What it does: thirteen lines in body become one. ContentView passes a binding to its selectedDie state; DiePicker reads and writes through it.
What next: build and run. Tap different dice. The highlight should move exactly as before, and a roll should use the die you selected. This proves the binding writes into ContentView's state, because performRoll() still reads selectedDie.
The app is running with D6 selected. You tap the D12 button. List, in order, which pieces of code run and which value changes: start at the Button inside DieButton and end with the screen updating. Which view owns the value that changes?
Step 7 — Create RollOptionsView
File: new file RollOptionsView.swift · Where: Views folder, SwiftUI View template · Action: Create file
import SwiftUI
struct RollOptionsView: View {
@Binding var quantity: Int
@Binding var modifier: Int
var body: some View {
VStack {
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: -20...20)
}
}
}
And the preview:
#Preview {
RollOptionsView(quantity: .constant(3), modifier: .constant(2))
.padding()
}
What it does: the two steppers, as one component with two bindings.
Why it is written this way:
- Each
Stepperneeds aBinding<Int>.RollOptionsViewdoes not own the numbers, so it receives bindings and passes them on with$quantityand$modifier. Here$on a@Bindingproperty gives you the binding itself, ready to hand to another view. A chain of bindings still points at one source of truth:ContentView's@State. - The modifier label now calls
RollResult.formatModifier(modifier), the shared function from Step 3. - The two steppers are wrapped in a
VStackbecause a view'sbodymust return one view (theVStackgroups them).
What next: the preview should show "Number of dice: 3" and "Modifier: +2". Pressing + in the preview does nothing because the bindings are constant. Build.
Step 8 — Use RollOptionsView in ContentView
File: ContentView.swift · Where: inside body, the two Stepper(...) lines below DiePicker(selection: $selectedDie) · Action: Replace
Before:
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)
After:
RollOptionsView(quantity: $quantity, modifier: $modifier)
What next: build and run. Change the number of dice and the modifier; roll. The labels, limits and results should behave exactly as before.
Step 9 — Create ResultView
File: new file ResultView.swift · Where: Views folder, SwiftUI View template · Action: Create file
The struct, its property and its column layout:
import SwiftUI
struct ResultView: View {
let roll: RollResult?
private let resultColumns = [
GridItem(.adaptive(minimum: 44))
]
The body. The contents of the if and else are the same views you had in ContentView, one indentation level shallower, with one change on the modifier line:
var body: some View {
VStack(spacing: 16) {
if let roll {
Text(roll.notation)
.font(.title2)
.fontWeight(.semibold)
ZStack {
Circle()
.fill(Color.orange.opacity(0.2))
.frame(width: 140, height: 140)
Text("\(roll.total)")
.font(.system(size: 64, weight: .bold))
}
LazyVGrid(columns: resultColumns, spacing: 8) {
ForEach(roll.values.indices, id: \.self) { index in
Text("\(roll.values[index])")
.font(.title3)
.fontWeight(.semibold)
.frame(width: 44, height: 44)
.background(Color.orange.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
if roll.modifier != 0 {
Text("Dice \(roll.subtotal), modifier \(RollResult.formatModifier(roll.modifier))")
.foregroundStyle(.secondary)
}
} else {
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
.frame(height: 140)
}
}
}
}
And two named previews, one per state:
#Preview("With a roll") {
ResultView(roll: RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2))
}
#Preview("Empty") {
ResultView(roll: nil)
}
What it does: everything about displaying the latest roll, or the prompt when there is none.
Why it is written this way:
rollis a plainlet, not a binding:ResultViewonly displays. Data flows one way, fromContentView'slatestRolldown.- The property is optional (
RollResult?) because "no roll yet" is a real state the view must show. The view handles both states, so the parent does not need anif. if let roll {is the shorthand forif let roll = roll {. Inside the braces,rollis unwrapped.- The views are wrapped in a
VStack(spacing: 16)sobodyreturns a single view. resultColumnsmoved here because only this view uses it; it isprivate.- The previews use the course's worked example (3D6 + 2 rolling 4, 2, 6) and
nil, so you can check both states without running the app.
What next: in the canvas you should see two preview tabs. "With a roll" shows "3D6 + 2", a total of 14, chips 4, 2, 6, and "Dice 12, modifier +2". "Empty" shows "Tap Roll Dice to begin". Build.
Step 10 — Use ResultView in ContentView and remove the leftovers
File: ContentView.swift · Where: inside body, the entire if let roll = latestRoll { ... } else { ... } block between RollOptionsView(...) and Button("Roll Dice") · Action: Replace
Before: the whole block, beginning with:
if let roll = latestRoll {
Text(roll.notation)
and ending with:
} else {
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
.frame(height: 140)
}
After:
ResultView(roll: latestRoll)
Now remove two things nothing uses any more:
File: ContentView.swift · Where: the let resultColumns = [ ... ] property near the top, and the func formattedModifier(_ value: Int) -> String { ... } function · Action: Delete
let resultColumns = [
GridItem(.adaptive(minimum: 44))
]
func formattedModifier(_ value: Int) -> String {
switch value {
case 0:
return "0"
case 1...:
return "+\(value)"
default:
return "\(value)"
}
}
Why delete formattedModifier now: both callers (the modifier stepper and the modifier line in the result) were replaced in Steps 8 and 10 and now use RollResult.formatModifier. There is one copy of the logic again.
What next: build and run. Roll with and without a modifier. The result display should look and behave as before. Stop and Run: the latest roll is restored, because loadHistory() still sets latestRoll, and ResultView displays whatever it is given.
Step 11 — Create HistoryRow
File: new file HistoryRow.swift · Where: Views folder, SwiftUI View template · Action: Create file
import SwiftUI
struct HistoryRow: View {
let roll: RollResult
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(roll.notation)
.font(.headline)
Text(roll.valuesDescription)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
VStack(alignment: .trailing) {
Text("\(roll.total)")
.font(.title2)
.fontWeight(.bold)
Text(roll.date.formatted(date: .omitted, time: .shortened))
.font(.caption2)
.foregroundStyle(.secondary)
}
}
}
}
#Preview {
HistoryRow(roll: RollResult(dieType: .d20, values: [17, 3], modifier: -4))
.padding()
}
What it does: one row of the history list: notation and individual values on the left, total and time on the right.
Why it is written this way: this is the content of the old ForEach body, minus the Divider. The divider is about how rows are separated in a list, which is the list's decision, not the row's. Keeping it out makes HistoryRow usable in other places (for example a future statistics screen) without a stray line. roll is non-optional here, because a row always represents a real roll.
What next: the preview shows "2D20 - 4", "17, 3", a total of 16 and the current time. Build.
Step 12 — Extract historySection and use HistoryRow
The history area uses history and clearHistory(), both of which belong to ContentView. Making it a separate component would need a binding or a closure for each. It is used only once, so a computed view property inside ContentView is the simpler choice. It gives the section a name and shortens body without creating a new type.
File: ContentView.swift · Where: inside struct ContentView, after the closing brace of body and before func rollDie · Action: Add
private var historySection: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("History")
.font(.title2)
.fontWeight(.bold)
Spacer()
Button("Clear") {
clearHistory()
}
.disabled(history.isEmpty)
}
if history.isEmpty {
Text("No rolls yet")
.foregroundStyle(.secondary)
}
ForEach(history) { roll in
HistoryRow(roll: roll)
Divider()
}
}
}
File: ContentView.swift · Where: inside body, the whole VStack(alignment: .leading, spacing: 12) { ... } block after the Roll Dice button's .tint(.orange) · Action: Replace
Before: the block that starts with VStack(alignment: .leading, spacing: 12) { and contains the History header, the "No rolls yet" text and the ForEach(history) with its full row layout.
After:
historySection
What it does: body now reads as an outline of the screen. The history area has a name and lives just below body. Each row is a HistoryRow.
Why a property and not a struct: a property can use history and call clearHistory() directly. A separate struct would need those passed in, adding plumbing without adding reuse. Both are valid; pick the one with less ceremony for the situation.
What next: build and run. Roll a few times and tap Clear. The history should look and behave as before.
Your body should now read:
var body: some View {
ScrollView {
VStack(spacing: 20) {
HStack {
Image(systemName: "dice.fill")
.font(.title)
.foregroundStyle(.orange)
Text("Dice Foundry")
.font(.largeTitle)
.fontWeight(.bold)
}
DiePicker(selection: $selectedDie)
RollOptionsView(quantity: $quantity, modifier: $modifier)
ResultView(roll: latestRoll)
Button("Roll Dice") {
performRoll()
}
.font(.title2)
.buttonStyle(.borderedProminent)
.controlSize(.large)
.tint(.orange)
historySection
}
.padding()
}
.onAppear {
loadHistory()
}
}
Step 13 — Mark ContentView's internals private
File: ContentView.swift · Where: the store property and each function below historySection · Action: Replace
Before:
let store = HistoryStore()
func rollDie(sides: Int) -> Int {
func rollDice(count: Int, sides: Int) -> [Int] {
func isValidQuantity(_ value: Int) -> Bool {
func performRoll() {
func clearHistory() {
func loadHistory() {
func saveHistory() {
After:
private let store = HistoryStore()
private func rollDie(sides: Int) -> Int {
private func rollDice(count: Int, sides: Int) -> [Int] {
private func isValidQuantity(_ value: Int) -> Bool {
private func performRoll() {
private func clearHistory() {
private func loadHistory() {
private func saveHistory() {
Add the private keyword at the start of each declaration. Change only the first line of each declaration; the bodies are unchanged.
What it does: nothing at run time. It tells the compiler, and every reader, that these are ContentView's internal machinery. If any other file tried to call performRoll(), the build would fail.
Why now: before this chapter everything lived in one file, so access control had little to protect. Now there are several files, and it matters which parts form a view's "public face" (its initializer inputs) and which are implementation details.
Why body is not private: body is required by the View protocol, and SwiftUI must be able to call it. Its access level cannot be lower than the protocol requires.
What next: build. There should be no errors or warnings. Your ContentView.swift should be about 130 lines, down from more than 200.
Step 14 — Run the regression checklist
Run the app and repeat every row of the table from Step 1. Each result should match. Also check:
- The previews of
DieButton,DiePicker,RollOptionsView,ResultView(both tabs) andHistoryRowall render. - The
ContentViewpreview renders the whole screen. - Persistence still works: roll, Stop, Run; the history and latest roll return.
- The history file is unchanged in format (optional:
catit as in Chapter 9). The models did not change except for the new static function, which is not stored data, so old files still load.
If something differs, use the step-by-step build history to narrow it down, and compare the affected file with Reference-Checkpoints/Checkpoint-10-Reusable-Components.
How the refactoring changed the code without changing behavior
| Before (Chapter 9) | After (Chapter 10) | Behavior |
|---|---|---|
Grid of Buttons in ContentView.body |
DiePicker + DieButton |
Same buttons, same tint rules, same state change via a binding |
Two Steppers in body |
RollOptionsView |
Same steppers, same ranges, bound to the same @State |
if let ... else result block in body |
ResultView(roll: latestRoll) |
Same views, same text; if let roll shorthand |
History VStack in body with inline rows |
historySection + HistoryRow |
Same header, button, rows and dividers |
formattedModifier in ContentView |
RollResult.formatModifier |
Same switch, one shared copy |
Everything internal |
Helpers and store private |
No run-time effect |
| All files at top level | Models/, Persistence/, Views/ |
No run-time effect |
The state, the functions that change it (performRoll, clearHistory, loadHistory, saveHistory) and the persistence code are untouched. Views only moved and gained inputs.
There is one honest, very small visual difference. In Chapter 9, the result views and the two steppers sat directly in the main VStack(spacing: 20). Now each group is wrapped in its own VStack: the result items are 16 points apart (VStack(spacing: 16)) and the two steppers use the default stack spacing. The screen looks the same at a glance, but if you compare screenshots side by side you may notice those items are slightly closer together. That is a layout tweak, not a behavior change; every control, value and action is identical.
Expected Results

Actual iOS Simulator screenshot of Checkpoint 10 after one 1D6 roll: the result circle, the die tile and a single history row. The rolled number on your device will differ.
The app should look and behave as it did at the end of Chapter 9 (apart from the slight spacing noted above). The difference is entirely in the Project navigator and the code.
Illustrative mockup — not a screenshot
Project navigator Simulator (unchanged by design)
DiceFoundry Dice Foundry
DiceFoundryApp.swift [ D4 ] [ D6 ] [ D8 ]
ContentView.swift [ D10] [ D12] [ D20]
Models Number of dice: 3 [ - | + ]
DieType.swift Modifier: +2 [ - | + ]
RollResult.swift 3D6 + 2
Persistence ( 14 )
HistoryStore.swift [4] [2] [6]
Views Dice 12, modifier +2
DieButton.swift [ Roll Dice ]
DiePicker.swift History Clear
HistoryRow.swift 3D6 + 2 14
ResultView.swift 4, 2, 6 9:41 AM
RollOptionsView.swift
Assets.xcassets
Each new file has a working preview in the canvas: two die buttons; the die grid with D20 highlighted; two steppers showing 3 and +2; the result view in "With a roll" and "Empty" tabs; and a single history row for 2D20 - 4 showing a total of 16.
Reading This Like a Developer
Where execution begins. Unchanged: DiceFoundryApp → WindowGroup → ContentView. When SwiftUI evaluates ContentView.body, it now creates DiePicker, RollOptionsView, ResultView and reads historySection, which create DieButtons and HistoryRows in turn. .onAppear still loads the history.
Which variables hold state. Only ContentView's five @State properties. No child view has @State. Children hold either plain let inputs (DieButton, ResultView, HistoryRow) or @Bindings (DiePicker, RollOptionsView). This makes the data flow easy to audit: to find where any value lives, go to ContentView.
How data passes between views.
- Down, read-only:
latestRoll→ResultView.roll; each history element →HistoryRow.roll;dieTypeand the computedisSelected→DieButton. - Down, read-write:
$selectedDie→DiePicker.selection;$quantity,$modifier→RollOptionsView→ eachStepper. - Up, as an event:
DieButton.action, a closure created inDiePicker, which writesselection.
Which code runs when a die button is tapped. Button(action: action) in DieButton calls action → the closure from DiePicker runs selection = dieType → the binding writes ContentView.selectedDie → SwiftUI sees a @State change and re-evaluates ContentView.body → a new DiePicker is created → each DieButton gets a new isSelected → the tints update.
Which code runs when Roll Dice is tapped. Unchanged: performRoll() in ContentView. The new latestRoll flows into ResultView on the next render; the new history flows into historySection and its rows.
Business logic versus presentation. The child views are pure presentation: they decide how things look and report taps. Business rules (how to roll, validation, history limits, saving) remain in ContentView's private functions and in the models. Formatting a modifier moved into the model because it is shared knowledge about roll data. Chapter 13 moves the business logic out of ContentView entirely; the components you built here will not need to change.
ContentView.quantity is 1. The user taps + on the "Number of dice" stepper twice. The stepper lives in RollOptionsView, which received $quantity from ContentView. What is the value of ContentView.quantity now? What is RollOptionsView.quantity? If the user then taps Roll Dice, how many dice does performRoll() roll, and why?
Suppose someone changes DiePicker to declare @State var selection: DieType = .d6 instead of @Binding var selection: DieType, and ContentView creates it as DiePicker(). The user taps D20 and then Roll Dice. Which button is highlighted, and which die is rolled? Why?
Generated SwiftUI projects often have dozens of small views. To orient yourself quickly: (1) find the @State (or @Observable model, Chapter 13) that owns each value; (2) for each child view, read only its stored properties, which are its inputs; @Binding means "this view can change the parent's data", a closure property means "this view reports an event"; (3) look for @State in children that duplicates a parent's value, which is the most common source of "the UI shows one thing but the app does another" bugs. When directing an assistant, be explicit: "Extract the history row into HistoryRow taking let roll: RollResult; keep all state in ContentView."
Troubleshooting
"Cannot find 'DiePicker' in scope" (or any new view)
Cannot find 'DiePicker' in scope
Likely causes: the file is not in the app target, the struct name does not match (case matters), or the file was created as a different template with a different struct name.
Investigate: select the file, open the File inspector (⌥⌘1), and check Target Membership. Open the file and confirm struct DiePicker: View.
Passing a value where a binding is expected
Cannot convert value of type 'DieType' to expected argument type 'Binding<DieType>'
Meaning: you wrote DiePicker(selection: selectedDie) without $. A @Binding property needs a binding, not a value.
Fix: DiePicker(selection: $selectedDie). The reverse mistake, ResultView(roll: $latestRoll), gives a similar message about converting Binding<RollResult?> to RollResult?: ResultView takes a plain value.
A preview fails because a binding is missing
Missing argument for parameter 'selection' in call
Meaning: the preview creates the view without supplying the binding.
Fix: use a constant binding: DiePicker(selection: .constant(.d20)).
Taps in a preview do nothing
Meaning: not an error. .constant(...) bindings ignore writes, and DieButton's preview passes empty closures. Test interaction in the simulator, or in the ContentView preview, where real @State exists.
"Cannot find 'columns' in scope" or "Cannot find 'formattedModifier' in scope"
Meaning: you deleted a property or function while code in ContentView still used it.
Fix: follow the order in the steps: replace the code that uses columns (Step 6), resultColumns and formattedModifier (Steps 8 and 10) first, then delete. If you see this, either restore the deleted item temporarily or finish the replacement.
"'performRoll' is inaccessible due to 'private' protection level"
Meaning: code outside ContentView is calling a member you made private. This would happen if, for example, you tried to call performRoll() from a child view.
Fix: don't widen access to make it compile. Pass a closure into the child instead (the same pattern as DieButton.action), so the child does not depend on ContentView's internals.
A private stored property breaks the initializer
If you mark a stored property private and it has no default value, Swift makes the memberwise initializer private too, and the parent can no longer create the view. You will see a message similar to "'DieButton' initializer is inaccessible due to 'private' protection level".
Fix: leave input properties (the ones the parent must supply) internal. Only make properties private when they have a default value, like columns and resultColumns.
The layout looks slightly different
If a group of controls is spaced a little differently from Chapter 9, check the VStack you wrapped them in. RollOptionsView uses a plain VStack and ResultView uses VStack(spacing: 16), as in the reference. See "How the refactoring changed the code without changing behavior".
A moved file disappeared or the project shows it in red
Meaning: the file was moved outside Xcode, or a move was interrupted. Red file names mean Xcode cannot find the file on disk.
Investigate: in Finder, locate the file (right-click the project → Show in Finder). Drag it back into the correct folder in Xcode's Project navigator rather than moving it in Finder, and recheck target membership.
Knowledge Check
- What is refactoring, and how can you check that a refactoring did not change behavior?
- Why does
DiePickeruse@Binding var selectionwhileResultViewuseslet roll? What would go wrong ifDiePickerused@Stateinstead? - What does
$produce when applied to a@Stateproperty, and why doStepperandRollOptionsViewneed it? - Why did
formattedModifiermove toRollResultas astaticfunction instead of being copied intoRollOptionsViewandResultView? - What is the default access level in Swift, and why are
ContentView's functions markedprivatewhileDieButton'sdieType,isSelectedandactionare not?
Independent Challenge
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.
Extract the Roll Dice button from ContentView into a new component, Views/RollButton.swift. Requirements: RollButton has no state; it receives what should happen when tapped through a closure property; it keeps the same title and modifiers (.font(.title2), bordered prominent, large, orange tint); it has a #Preview. ContentView uses it so tapping it still calls performRoll(), which stays private. Acceptance criteria: the project builds with no warnings; the app behaves exactly as before (run the regression checklist); the preview shows the button.
The individual dice in ResultView are drawn by a six-modifier Text inside the ForEach. Extract it into Views/ValueChip.swift, a view that displays one die value in the orange rounded square. Requirements: one input property for the value; a preview showing several chips side by side; ResultView uses it inside its ForEach. Acceptance criteria: builds without warnings; results look identical; the ResultView previews still render.
Progressive hints are in the Chapter 10 Exercises document. Do challenges on a Git branch.
Chapter Completion Checklist
- The Project navigator has
Models,PersistenceandViewsfolders, and every file has DiceFoundry target membership. RollResulthasstatic func formatModifier(_:), andContentViewno longer hasformattedModifier.DieButton,DiePicker,RollOptionsView,ResultViewandHistoryRowexist inViews, each with a working preview.ContentView.bodyuses the components andhistorySection.ContentViewno longer hascolumnsorresultColumns.- The store,
historySectionand all ofContentView's functions areprivate. - All
@Statelives inContentView; no child view has@State. - You ran the Step 1 checklist before and after, with matching results.
- Persistence still works after the refactor.
- You can explain the difference between passing
latestRolland passing$selectedDie. - The project builds with no errors or warnings.
Development Checkpoint
Commit the refactoring as its own commit, so the history shows clearly that this change reorganized code without adding features.
In Xcode: Integrate → Commit... (or Source Control → Commit...). Moved files appear as deletions plus additions or as renames; include them all. Or in Terminal:
git add -A
git commit -m "Chapter 10: Extract reusable components and organize files"
git tag chapter-10
To compare with the reference, open Reference-Checkpoints/Checkpoint-10-Reusable-Components/DiceFoundry/. Its folder structure should match yours: Models/, Persistence/, Views/, plus ContentView.swift and DiceFoundryApp.swift. Compare individual files with FileMerge or diff -u, for example:
diff -u Reference-Checkpoints/Checkpoint-10-Reusable-Components/DiceFoundry/Views/DiePicker.swift \
/path/to/your/DiceFoundry/DiceFoundry/Views/DiePicker.swift
The template-generated comment header in your new files may differ (Xcode adds "Created by" lines); that is fine.
Prediction Answers
Trace a tap through the binding. DieButton's Button(action: action) calls its stored action closure. That closure was created in DiePicker's ForEach and runs selection = .d12. selection is a @Binding, so the write goes to ContentView's @State private var selectedDie, which becomes .d12. ContentView owns the value. SwiftUI notices the @State change, re-evaluates ContentView.body, which creates a new DiePicker(selection: $selectedDie); its ForEach creates DieButtons whose isSelected is now true only for D12, and the screen updates the tints.
Bindings in a chain. Both read 3. There is only one stored value, ContentView.quantity; RollOptionsView.quantity is a binding to it, and the Stepper received $quantity from RollOptionsView, which is the same binding passed along. Each tap writes through the chain to ContentView's @State. performRoll() reads ContentView.quantity, so it rolls 3 dice.
What if the child owned the state? D20 is highlighted, but a D6 is rolled. The @State inside DiePicker is a separate copy owned by the picker. Tapping D20 changes the picker's copy, so the picker re-renders with D20 highlighted, but ContentView.selectedDie never changes and is still .d6, which is what performRoll() uses. Two sources of truth disagree. This is exactly the bug @Binding prevents.