Chapter 12 — Debugging and Testing
Dice Foundry rolls, records, and saves correctly on the path you have been testing by tapping. Real software fails in the corners you did not tap: a quantity of zero, a random range that is one off, a total that forgets the modifier, a history that reappears after a relaunch. In this chapter you learn three skills that catch those failures. You learn to read what the compiler is telling you, to use the debugger to see the values that actually exist while the app runs, and to write automated tests that check the rules of the app every time you change the code.
Testing has one prerequisite, and you will meet it in this chapter. The random-number code currently lives inside ContentView, and it calls Int.random(in:) directly. A test cannot predict the output of a random number generator, so it cannot say "a roll of three six-sided dice with a modifier of two must total between five and twenty." You will move the dice logic into a small DiceRoller type that accepts its source of randomness from outside. That one design change is what makes the rest of the chapter possible.
Learning Objectives
By the end of this chapter you will be able to:
- Distinguish compile-time, runtime, and logic errors, and say which kind of tool finds each one.
- Read a compiler diagnostic: the file, the line, the column, the message, and the cascade of follow-on errors that usually comes after the first one.
- Set a breakpoint, pause the app, and inspect values in the Variables view and the debug console with
pandpo. - Reproduce a bug, reduce it to the smallest case, change one thing at a time, and verify the result.
- Explain why code that calls a random number generator directly is hard to test, and how injecting the randomness through a stored closure fixes it.
- Move logic out of a view into a plain
structthat has no user interface. - Create a test target with Swift Testing and write tests with
@Test,#expect,#expect(throws:), and@Test(arguments:). - Write boundary tests that check values at the edges of an allowed range.
- Explain why some bugs, such as forgetting to save, are not caught by unit tests and need a different check.
- Run the test suite, read a failing result, and identify the broken rule from the failure message.
Concept Explanation
Three kinds of failure
Software can go wrong at three different moments, and each moment has a different tool that catches it.
Compile-time errors happen when Xcode translates your Swift into an app. The compiler refuses to build the project, so nothing runs at all. A misspelled name, a value of the wrong type, and a missing brace are compile-time errors. They are the cheapest errors to fix because the feedback is immediate and points at the line.
Runtime errors happen after the app builds and starts. The app crashes, or an operation fails while the app is running. An array index that is out of range, or a file that cannot be read, are runtime errors. The app may print a message to the debug console and carry on, or it may stop with a crash report. You find them by running the app and watching what happens.
Logic errors are the most dangerous. The project builds, the app runs, nothing crashes, and the answer is simply wrong. A total that is two points too low is a logic error. The compiler cannot know your rules, because the rules exist only in your head and in the requirements. The only way to catch a logic error is to check the output against an expected answer, either by hand or with a test.
A configuration file with invalid syntax fails validation before the service starts: that is the compile-time error. A service that starts and then crashes on its first request, because a dependency is missing, is the runtime error. A service that starts, responds, and returns the wrong data is the logic error, and it is the one that goes unnoticed for weeks unless someone checks the output. Your monitoring checks for the last kind are what a test suite is in software.
Reading a compiler diagnostic
When the build fails, Xcode shows a red marker in the Issue navigator and in the editor. Each entry has the same parts:
ContentView.swift:<line>:<column>: error: Cannot find 'reslt' in scope
The message is shown in the form similar to the one above: the file name, the line number, the column, the severity (error or warning), and the text. The text is written for a compiler, not for a human, so read it slowly and literally. Cannot find 'reslt' in scope means the compiler looked for a name called reslt and did not find one. Either the name is misspelled, or the thing you meant to name was never declared.
Two habits matter more than memorizing messages.
First, fix the first error first. The compiler reads the file from top to bottom, and one mistake can produce a cascade of follow-on errors that disappear once the first is fixed. A list of twelve errors is often one error and eleven consequences.
Second, read the column as well as the line. A column points to the exact token the compiler could not handle. In a long line, the column is the fastest way to see which part of the line is wrong.
Warnings are not errors, but they are the compiler's way of saying "this will probably bite you." This course's reference code builds with zero warnings, and you should treat any warning in your own project the same way.
Breakpoints, the Variables view, and the console
A compiler error tells you what is wrong with the code. A breakpoint tells you what is true while the code runs. A breakpoint is a marker on a line. When the app reaches that line, it pauses before running the line, and Xcode shows you the state of the program at that exact moment.
If you have ever attached a debugger to a stuck process, or taken a core dump of a service that hangs, you already know the idea. The process stops at a known point; you read its memory; you resume. A breakpoint in Xcode works the same way, except the memory is your app's variables, and "resume" means "run the next line".
When the app is paused, three things help you read it.
- The Variables view, at the bottom of the window, lists the local values and the properties of
selfthat are visible at that line, with their current contents. - The debug console accepts commands. The command
po(print object) prints a value as a human-readable description, andpprints the value together with its type. In Xcode you typepo quantityin the console, and the console shows the current value ofquantity. - The step controls in the debug bar run the next line (step over), go into a function call (step into), or leave the current function (step out). They let you move through the code one line at a time while you watch the values change.
You will use all three in the Guided Implementation.
Reproduce, isolate, and fix
Experienced troubleshooters work from a method, not from intuition. The method is the same whether the system is an iPhone app or a storage array:
- Reproduce. Write down the exact steps that cause the problem. A bug you cannot reproduce is a bug you cannot prove fixed.
- Isolate. Reduce the steps. Does the problem happen with one die? With a modifier of zero? After a relaunch? Each answer removes part of the system from suspicion.
- Hypothesize. State one specific cause: "the total is computed from the wrong variable." A hypothesis is testable; a vague feeling is not.
- Change one thing. Make one change and observe. If you change three things and the problem goes away, you do not know which change mattered.
- Verify. Run the reproduction steps again, and ideally run a test that would have failed before the fix and passes after it.
The rest of this chapter follows that method. Each deliberate bug in the Guided Implementation is a small, controlled reproduction, and each fix is a single change you can verify.
Why randomness blocks testing
A test is a promise that the same input always produces the same output. That promise is easy for roll.total when the dice values are known, and impossible when the dice values come from Int.random(in:). Every run gives different numbers, so a test cannot say "the total must be 14," because the total is different each time.
The standard solution is to separate the source of randomness from the rule that uses it. The rule (add the dice, add the modifier, build a record) stays in place. The source (where each die value comes from) becomes something the caller can replace. In production it is the real random number generator. In a test it is a predictable function that always returns the same value.
Swift lets you store a function in a property. The type of the property looks like this:
var randomValue: (ClosedRange<Int>) -> Int
Read it piece by piece. (ClosedRange<Int>) is the parameter list: the function takes one closed range of integers, such as 1...6. -> Int is the return type: the function returns one integer. A value of that type is any function that fits the shape, including a closure. A closure is a block of code you can store and pass around, which you first met as the action of a button in Chapter 4.
Here is the production version, which you will type in the Guided Implementation:
var randomValue: (ClosedRange<Int>) -> Int = { range in
Int.random(in: range)
}
The default value is a closure that calls the real random number generator. The test version is a closure that returns a fixed number. Because the property is a parameter of the type's initializer, a test can replace the default without touching the code under test. This technique is called dependency injection: the dependency (the source of randomness) is handed in from outside rather than created inside the code that needs it. Chapter 13 uses the same idea for the view model.
You could define a RandomSource protocol with a next(in:) method and write two conforming types. That works, and large projects often do it. For a single function, a stored closure is shorter and just as clear. Use the heavier tool when you need several related functions, not for one.
Unit tests and the Swift Testing framework
A unit test exercises one small piece of code, such as a function or a type, and checks its result against an expected value. Unit tests do not tap buttons, and they do not look at the screen. They call your code directly and compare the answer with what the rules say it should be.
Xcode runs unit tests from a separate test target: a second build product that contains your test code and loads your app's code so the tests can use it. You keep the app target and the test target separate so that the app you ship does not contain the tests.
Apple provides the Swift Testing framework for writing these tests. It gives you three tools for almost every test you will write:
@Testmarks a function as a test. Xcode finds every function marked this way and runs it.#expect(...)checks a condition. If the condition isfalse, the test fails and Xcode reports the expression and the values it compared.@MainActoron a test type is a marker you will see on every test type in this course. It tells Swift that the tests run on the main thread, the same as the app's own code. Swift 5 language mode does not strictly require it, but Swift 6 does, and Chapter 13 explains the main thread in more detail.
Older projects and many AI-generated samples use an earlier framework called XCTest, with functions such as XCTAssertEqual. You may see it in code you read. The ideas are the same: run code, compare the result, report a failure.
AI-generated tests often look thorough and check very little. A common pattern is a test that calls a function, stores the result in a variable, and then asserts that the variable equals what the function just returned, which can never fail. Before you trust a test, ask what would make it fail. If the answer is "nothing," the test documents the code rather than checking it. The tests in this chapter each state a rule from the requirements, such as "3D6 + 2 totals 14," and each would fail if that rule broke.
Boundary tests and parameterized tests
Most real bugs live at the edges of a range. A quantity of 10 works and a quantity of 11 does not; a die value of 6 is valid and a value of 7 for a d6 is a bug. A boundary test checks the values at the edges, not only comfortable values in the middle. For Dice Foundry, the boundaries are the smallest and largest quantities, the smallest and largest modifiers, and the lowest and highest face of each die.
When the same check must run for many inputs, a parameterized test runs one function once for each value in a list. In Swift Testing you add arguments: to @Test:
@Test(arguments: DieType.allCases)
func someRuleHoldsForEveryDie(dieType: DieType) {
Xcode runs that function once for each case in DieType.allCases, and each run is reported separately, so you see exactly which die failed.
Closure types and capturing a variable
The tests you write later use a closure that records the range it was asked for. The closure can change a variable that lives outside itself. Swift allows this: a closure can capture a variable declared in the surrounding code and change it. You will see it in rollRequestsTheCorrectRangeForEachDie, where the closure stores the range it receives in a variable declared just above the DiceRoller is created.
A test creates let roller = DiceRoller(randomValue: { _ in 5 }) and then calls roller.roll(.d4, quantity: 100, modifier: -3). The injected function always returns 5, even though a d4 has only four faces. Before you read on, predict:
- How many values does the returned
RollResultcontain? - What is the first value in
values? - What is
subtotal, and what istotal?
Write your answers down. Answers are in the Prediction Answers section at the end of the chapter.
Notice what the trace shows. DiceRoller does not check that the random value is a legal die face. That is correct behavior for this design: the random source is supposed to be correct, and tests that use a fake source are testing the rules around it, not the random source itself. A second test checks that the real source stays in range, which you will meet later in this chapter.
What unit tests do not cover
Unit tests check rules. They do not check the screen, the order in which a button changes state, or what happens after the app is force-quit and reopened. A bug in clearHistory() that forgets to save is perfectly invisible to a test of DiceRoller, because clearHistory() lives in ContentView, and ContentView is hard to test directly. In those cases you use a second kind of check: a manual test script, a short list of steps you run by hand after each change, with the expected result of each step written down. Chapter 13 moves the logic that needs testing out of the view, which makes many of those checks automatic. In this chapter you will write one manual script and use it.
Syntax Breakdown
This chapter introduces the syntax for a plain type with stored behavior, for ranges used as values, and for tests. Each item is shown in the form it takes in the code you will type.
struct DiceRoller { and static properties
struct DiceRoller {
static let quantityRange = 1...10
static let modifierRange = -20...20
| Token | Meaning |
|---|---|
struct |
Declares a value type, the same keyword you used for ContentView and RollResult. |
DiceRoller |
The name of the new type. It has no user interface and conforms to no protocol. |
static |
The property belongs to the type itself, not to any one DiceRoller value. You read it as DiceRoller.quantityRange. |
let |
The value cannot change after it is set. |
quantityRange |
The name, used by RollOptionsView and by roll. |
1...10 |
A closed range: every integer from 1 through 10, including both ends. |
Putting the limits on DiceRoller gives one source of truth. Before this chapter the limits lived in three places: in RollOptionsView's steppers, in isValidQuantity, and in the comment in your head. Now the stepper and the roll function both read the same value.
var randomValue: (ClosedRange<Int>) -> Int = { range in ... }
| Token | Meaning |
|---|---|
var |
A stored property that can be replaced, which is what lets a test replace it. |
randomValue |
The name of the property. |
: |
Introduces the type. |
(ClosedRange<Int>) -> Int |
The type: a function that takes one closed range of integers and returns one integer. |
= |
Introduces the default value. |
{ range in ... } |
A closure. range is the parameter name, and in separates the parameter list from the body. |
Int.random(in: range) |
The body: it asks the system for one random integer within the range. |
Because the property is var and has a default value, the initializer that the compiler creates for the struct accepts it as an optional parameter. DiceRoller() uses the default. DiceRoller(randomValue: ...) replaces it.
func roll(_ dieType: DieType, quantity: Int, modifier: Int) -> RollResult
func roll(_ dieType: DieType, quantity: Int, modifier: Int) -> RollResult {
| Token | Meaning |
|---|---|
func roll |
Declares a method named roll on DiceRoller. |
_ dieType: DieType |
The first parameter has no argument label, because of the underscore, so you call it as roll(.d6, ...). The name inside the function is dieType. |
quantity: Int |
The second parameter has the argument label quantity, and callers must write it. |
-> RollResult |
The method returns a RollResult, the same record you built in Chapter 8. |
The labels read like a sentence at the call site: roller.roll(.d6, quantity: 3, modifier: 2). The first argument is unlabeled because the die is the thing being rolled, and the other two are labeled because they are options.
min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound)
let safeQuantity = min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound)
Read this from the inside out.
| Token | Meaning |
|---|---|
max(quantity, Self.quantityRange.lowerBound) |
The larger of the requested quantity and the lowest allowed quantity. If the request is 0, the result is 1. |
min(..., Self.quantityRange.upperBound) |
The smaller of that result and the highest allowed quantity. If the request is 99, the result is 10. |
Self |
Inside a type's own code, Self refers to that type. Self.quantityRange means DiceRoller.quantityRange. |
.lowerBound, .upperBound |
The two ends of a range. Every range has them. |
let safeQuantity |
Names the clamped result. |
This pattern is called clamping: forcing a value into a range by limiting it at both ends. The min and max functions are built into Swift. Nothing about this line is special except its order, which you should read innermost first.
Chapter 7's version printed Invalid quantity and did nothing when the quantity was out of range. Clamping always produces a roll, which is what a user of the Stepper expects. The Stepper already prevents out-of-range values in the interface, so the clamp is a second line of defense for code paths that do not go through the Stepper. You could argue for either design. The important part is that the choice is made on purpose and tested.
for _ in 1...safeQuantity { ... }
for _ in 1...safeQuantity {
| Token | Meaning |
|---|---|
for |
Starts a loop, which you met in Chapter 6. |
_ |
A placeholder meaning "I do not need the loop value". You only need to repeat the body. |
1...safeQuantity |
The loop runs once for each integer from 1 through safeQuantity. |
values.append(randomValue(1...dieType.sides))
values.append(randomValue(1...dieType.sides))
Calling randomValue looks like calling a function, because it is one. The stored closure is invoked with the range 1...dieType.sides, which for a d6 is 1...6. The number it returns is appended to values. In production the closure calls the real generator. In a test it returns whatever the test chose.
Test declarations
@MainActor
struct DiceRollerTests {
@Test func rollUsesInjectedValues() {
let roller = DiceRoller(randomValue: { _ in 4 })
let roll = roller.roll(.d6, quantity: 3, modifier: 0)
#expect(roll.values == [4, 4, 4])
}
| Token | Meaning |
|---|---|
@MainActor |
Marks the test type as running on the main thread, as described in the Concept Explanation. |
struct DiceRollerTests |
A test type. Swift Testing creates a new instance of it for each test, so state does not leak between tests. |
@Test |
Marks the next function as a test that Xcode should run. |
func rollUsesInjectedValues() |
The test function. The name should state the rule being checked. |
DiceRoller(randomValue: { _ in 4 }) |
Creates a roller whose random source always returns 4. _ in means the closure ignores its range parameter. |
#expect(roll.values == [4, 4, 4]) |
Checks a condition. == compares two arrays element by element. |
#expect(throws: (any Error).self) { ... }
#expect(throws: (any Error).self) {
try store.load()
}
| Token | Meaning |
|---|---|
#expect(throws: ...) |
Passes only if the closure that follows throws an error. |
(any Error).self |
The type any Error, which means "a value of any type that conforms to the Error protocol." Swift needs this type so it can check for any kind of thrown error. You do not need to master the any keyword now. |
{ try store.load() } |
The trailing closure: the code that should throw. try marks a call that can throw. |
Data("not json".utf8) and URL.temporaryDirectory
try Data("not json".utf8).write(to: store.fileURL)
| Token | Meaning |
|---|---|
"not json".utf8 |
The UTF-8 bytes of the string, which is the form a file stores. |
Data(...) |
Wraps those bytes in a Data value, which is what a file write needs. |
.write(to:) |
Writes the data to a file, as you did in Chapter 9 with save. |
URL.temporaryDirectory is a folder that the system provides for temporary files, the same way URL.documentsDirectory gives you the Documents folder that Chapter 9 used. Tests write into the temporary folder so they never touch the real roll history.
@Test(arguments: DieType.allCases)
@Test(arguments: DieType.allCases)
func realRandomValuesStayInRange(dieType: DieType) {
| Token | Meaning |
|---|---|
arguments: |
The list of values the test should run with. |
DieType.allCases |
Every case of DieType, which you first used in Chapter 5. |
dieType: DieType |
The parameter that receives one case on each run. |
@testable import DiceFoundry
import Testing
@testable import DiceFoundry
| Token | Meaning |
|---|---|
import Testing |
Brings in the Swift Testing framework. |
@testable |
An attribute that lets the test target see internal code in the app, such as DiceRoller, which would otherwise be hidden from other modules. |
import DiceFoundry |
The app module. Its name is the product name you chose in Chapter 1. |
Guided Implementation
This chapter has three parts of work. In Part A you deliberately break your project in small ways and read the compiler's messages. In Part B you pause the running app with a breakpoint and inspect its values. In Parts C to F you move the dice logic into DiceRoller, create a test target, write the tests, and then break the logic on purpose to watch the tests catch it.
Before you begin:
- Open your Dice Foundry project. It should match the state at the end of Chapter 11. If you took the Chapter 11 challenges on a branch, return to
mainfirst (git switch main). - Show the Project navigator with ⌘1 if it is hidden. Open
ContentView.swift. - Run the app once with ⌘R, tap Roll Dice, and confirm that it works. You are about to change code, so you want a known-good starting point.
Each experiment in Part A is followed by a step that restores the original line. If you prefer, use Edit → Undo (⌘Z) instead. Either way, check the file after each step. The Git commit you make at the end of this chapter is the safety net for the whole chapter.
Part A — Read the compiler's messages
You will make four small, deliberate mistakes. Each one is a common real-world error. Build after each change with ⌘B, read the first error, and then undo the change before you continue.
Step 1 — A misspelled name
File: ContentView.swift · Where: inside performRoll(), the line that reads latestRoll = roll · Action: Replace
Before:
latestRoll = roll
After (this line will not compile):
latestRoll = reslt
What it does: asks for a variable named reslt. No such name exists, because the value you created on the line above is named roll.
What should happen: the build fails. The Issue navigator (⌘5) lists an error similar to the one below, and the editor shows a red marker on the line.
ContentView.swift:<line>:<column>: error: Cannot find 'reslt' in scope
Investigation: read the name in quotes, then search the file for the same name. A typo gives you one error at one place. Undo the change now: replace reslt with roll so the line reads latestRoll = roll again. Build with ⌘B and confirm the error is gone.
Step 2 — A type mismatch
File: ContentView.swift · Where: inside performRoll(), directly after the line that creates roll · Action: Add
let label: String = roll.total
What it does: declares a constant that is required to hold text, but gives it the total, which is a whole number.
What should happen: the compiler rejects the line with a message similar to the one below. roll.total is an Int, and a String is required.
Cannot convert value of type 'Int' to specified type 'String'
Why it matters: Swift checks types at compile time. The fix is to convert the number explicitly (for example, String(roll.total)), or to change the declared type. Which one is right depends on what the label is for. Delete the line now, so performRoll() is back to its original form, and build again.
Step 3 — A missing state declaration
File: ContentView.swift · Where: the property declaration @State private var rollCount: Int = 0 near the top of ContentView · Action: Replace
Before:
@State private var rollCount: Int = 0
After (this will not compile):
private var rollCount: Int = 0
What it does: removes the @State wrapper. The property is now an ordinary stored value of the view struct, and the view is a struct, so it is not allowed to change its own stored values.
What should happen: the build fails at the line in performRoll() that reads rollCount += 1, with a message similar to the following.
Cannot assign to property: 'self' is immutable
Why it matters: this is one of the most common SwiftUI mistakes, and AI-generated code makes it often. @State is what tells SwiftUI "this value belongs to this view, and changing it should redraw the screen." Without it, the assignment has nowhere legal to go. Restore the line now.
File: ContentView.swift · Where: the same property declaration · Action: Replace
@State private var rollCount: Int = 0
Step 4 — A missing brace
File: ContentView.swift · Where: the closing brace } that ends performRoll() · Action: Delete
What it does: removes the brace that closes performRoll(). Every opening brace needs a matching closing brace, and the compiler tracks the pairs.
What should happen: Xcode reports one or more errors that usually appear far from the missing brace, often at the next function or at the very end of the file. A message similar to the following is typical.
Expected '}' in struct
Why it matters: the error points to where the parser ran out of patience, not necessarily to the mistake. When you see a brace error, do not look at the reported line first. Look at the last function you edited, and check that each func has one { and one }. Xcode's ⌃I shortcut re-indents the code, and the indentation mismatch usually shows where a brace is missing. Restore the brace now: add a line containing } directly after the last line of performRoll(), at the same indentation as the private func line. Build and confirm that the error is gone.
In all four experiments, the first error in the Issue navigator was the one that mattered. The later errors were consequences. Fix the first error, build again, and let the compiler tell you about the next one.
Part B — Pause the app with a breakpoint
Part A dealt with code that would not compile. Now you look at code that compiles and runs. In this part you do not change any code.
Step 5 — Set a breakpoint in performRoll()
A breakpoint is a marker that Xcode keeps in your local Xcode user data, not in your Swift source. Setting one does not change your code, so there is no EDIT callout for it.
- In
ContentView.swift, find the linelatestRoll = rollinsideperformRoll(). - Click in the gutter, the narrow column to the left of the line numbers, on the same line. A blue arrow appears. That is the breakpoint.
- Confirm that the breakpoint is on the line that assigns
latestRoll, not on the line above it.
Step 6 — Run and roll until the app pauses
- Press ⌘R to run the app in the Simulator.
- Set the die to a D6 and the quantity to 3, using the Stepper.
- Tap Roll Dice.
The app stops at the breakpoint. The line with the arrow is highlighted, and the debug area at the bottom of the window appears. The line has not run yet: latestRoll still holds its old value.
Step 7 — Inspect the values
- In the Variables view, expand
rollif needed. You should see itsdieType,values,modifier, anddate. Thevaluesentry lists the dice you just rolled, for example three numbers between 1 and 6. - Click in the debug console at the bottom and type the following commands, pressing Return after each one.
po quantity
po selectedDie
po roll.values
p roll.total
Your output will differ in the numbers, but the form is similar to this.
3
d6
▿ 3 elements
- 0 : 4
- 1 : 2
- 2 : 6
(Int) $R0 = 14
po prints the object's description. p prints the value with its type in front, which is why the last line includes (Int). The $R0 is a temporary name the debugger gives the result so you can use it again in the console. The values you see depend on the random rolls, so your numbers will differ.
Before you press the step-over button, predict what latestRoll will be after the line runs. Then press step over and check the Variables view. Was your prediction correct?
Step 8 — Step over and then continue
- Click the step-over button in the debug bar. The arrow moves to the next line, which is
rollCount += 1. - Look at the Variables view.
latestRollnow refers to the roll you just made. You can see this by expandinglatestRollunderself. - Click the continue button (or press ⌃⌘Y) to let the app run to the end of the function.
- Stop the app with ⌘. and remove the breakpoint by clicking the blue arrow in the gutter.
You have now watched a value change from the inside. That is what a breakpoint is for: you do not guess what latestRoll contains, because you can see it.
Xcode's debug bar buttons and shortcuts change between versions. If a shortcut above does not work, use the button in the debug bar with the matching tooltip, and note the difference for next time.
Part C — Move the dice logic into DiceRoller
Now you change the code, and the reason is testability. The roll logic is currently inside ContentView, which also owns the layout, the state, and the file saving. A test cannot reach it without starting the user interface. You will move the dice logic into a new type, DiceRoller, that has no user interface, and inject the random source as described in the Concept Explanation.
The order of these steps matters. Each step must leave the project in a state that builds. The table shows the dependencies.
| Step | Change | Depends on |
|---|---|---|
| 9 | Create DiceRoller.swift |
nothing |
| 10 | Use DiceRoller ranges in RollOptionsView |
step 9 |
| 11 | Add a roller property to ContentView |
step 9 |
| 12 | Rewrite performRoll() to call the roller |
steps 9 and 11 |
| 13 | Delete rollDie, rollDice, and isValidQuantity |
step 12 |
If you delete the old functions before you rewrite performRoll(), the build fails with an error about rollDice or isValidQuantity not being found. That is a useful lesson: the old functions are still in use until the line that calls them has been replaced.
Step 9 — Create the Logic folder and DiceRoller.swift
First create a folder for the new type, following the same pattern as the Models, Persistence, and Views folders from Chapter 10.
- In the Project navigator, right-click the
DiceFoundryfolder (the one that containsContentView.swift) and choose New Group or New Folder. Name itLogic. Wording may differ slightly in your Xcode version. - Right-click the
Logicfolder and choose New File… (or New File from Template). Choose the Swift File template and name itDiceRoller.swift. Confirm that the target membership isDiceFoundry. - Replace the template contents with the code below. The template's comment header is fine to keep, as long as the file contains the code in the listing.
File: Logic/DiceRoller.swift (new) · Where: a new file in a new Logic folder inside DiceFoundry · Action: Create file
import Foundation
struct DiceRoller {
static let quantityRange = 1...10
static let modifierRange = -20...20
// The source of random numbers. The app uses Int.random(in:).
// Tests replace it with a predictable function.
var randomValue: (ClosedRange<Int>) -> Int = { range in
Int.random(in: range)
}
Add the roll method directly below the property, so the closing brace of the struct is at the end of the file:
func roll(_ dieType: DieType, quantity: Int, modifier: Int) -> RollResult {
let safeQuantity = min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound)
var values: [Int] = []
for _ in 1...safeQuantity {
values.append(randomValue(1...dieType.sides))
}
return RollResult(dieType: dieType, values: values, modifier: modifier)
}
}
What it does: DiceRoller contains the two rules that used to live in ContentView. The ranges are constants that both the view and the tests can read. The randomValue property is the random source. The roll method checks and clamps the quantity, calls randomValue once for each die, and returns a complete RollResult.
Why it is written this way: the struct has no @State, no layout, and no reference to any view, so you can create one in a test without starting the app's interface. The static ranges belong to the type, not to any roller, because they are rules rather than properties of one roller. The randomValue property is an ordinary var so tests can replace it.
What should happen: the build succeeds. DiceRoller is not used yet, so nothing in the app changes. The file appears in the Project navigator under Logic.
The let safeQuantity line is about 100 characters. Xcode does not wrap lines for you, and the reference code keeps the line as one piece so it matches your copy character for character. You may wrap it, but then the line will no longer match the checkpoint.
Step 10 — Use the DiceRoller ranges in RollOptionsView
The Stepper limits are the same rules as DiceRoller's ranges. Using the constants keeps the two in agreement.
File: Views/RollOptionsView.swift · Where: inside body, the two Stepper lines · Action: Replace
Before:
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
Divider()
Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: -20...20)
After:
Stepper("Number of dice: \(quantity)", value: $quantity, in: DiceRoller.quantityRange)
Divider()
Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: DiceRoller.modifierRange)
What it does: the stepper's allowed values now come from DiceRoller. If you later change the maximum number of dice, you change one line in DiceRoller.swift, and the stepper follows.
Why it is written this way: a value that appears in two places can drift apart. A stepper that allows 12 dice while the roll function clamps to 10 would be a quiet logic bug, and the constants prevent it.
What should happen: the build succeeds. The steppers behave exactly as before. Run the app, press the quantity stepper up to 10 and down to 1, and confirm the labels update as before.
Step 11 — Add a roller property to ContentView
File: ContentView.swift · Where: directly after the line private let store = HistoryStore(), near the top of ContentView · Action: Add
private let roller = DiceRoller()
What it does: creates one DiceRoller for the view, using the default random source.
Why it is written this way: let is used because the view never needs to replace the roller; it only calls it. The same pattern appears in the store line directly above, which you wrote in Chapter 9. The roller is created once, when the view is created, not once per roll.
What should happen: the build succeeds. Nothing calls the roller yet, so the app still uses the old functions.
Step 12 — Rewrite performRoll() to call the roller
This step replaces the body of performRoll() with a version that asks the roller for the values and does nothing else with the random numbers. Here is the existing function, for comparison.
File: ContentView.swift · Where: the function private func performRoll() · Action: Replace
Before:
private func performRoll() {
if isValidQuantity(quantity) {
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)
if history.count > HistoryStore.maximumCount {
history.removeLast()
}
saveHistory()
} else {
print("Invalid quantity: \(quantity)")
}
}
After:
private func performRoll() {
let roll = roller.roll(selectedDie, quantity: quantity, modifier: modifier)
latestRoll = roll
rollCount += 1
history.insert(roll, at: 0)
if history.count > HistoryStore.maximumCount {
history.removeLast()
}
saveHistory()
}
What it does: the function now makes one call, roller.roll, to get a complete RollResult. It then does the view-related work: it stores the result as the latest roll, increases rollCount so the animation and haptic fire, inserts the result at the front of the history, trims the history to 50 entries, and saves.
Why it is written this way: the view decides what to show and when to save; the roller decides what the dice are. The split is small, but it is the reason the roll rules can now be tested without a screen. Notice also what has been removed: the if isValidQuantity check and the print message. The roller clamps the quantity instead, so the function always produces a roll. That is a deliberate behavior change, and the Reading section explains it.
What should happen: the build succeeds with rollDie, rollDice, and isValidQuantity still in the file. Those three functions are now unused. The compiler does not report unused functions, so nothing reminds you to remove them. You will do that in the next step.
If you delete the three old functions before this step, the build fails with an error such as Cannot find 'rollDice' in scope. The message is correct: performRoll() was still calling it. Do step 12 first.
Step 13 — Delete the three functions that moved
File: ContentView.swift · Where: the three private func declarations between settingsSection and performRoll() · Action: Delete
Delete these three functions completely, including their braces and the blank lines between them:
private func rollDie(sides: Int) -> Int {
let roll = Int.random(in: 1...sides)
return roll
}
private func rollDice(count: Int, sides: Int) -> [Int] {
var rolls: [Int] = []
for _ in 1...count {
rolls.append(rollDie(sides: sides))
}
return rolls
}
private func isValidQuantity(_ value: Int) -> Bool {
value >= 1 && value <= 10
}
What it does: removes the old logic. The only copy of the dice rules is now in DiceRoller.
Why it matters: duplicated rules are how logic bugs are born. Two copies of the rule can disagree, and the tests you write next will check only one of them. Removing the copy means there is one thing to test.
What should happen: the build succeeds with no errors and no warnings. Confirm that the ContentView.swift file still contains performRoll(), clearHistory(), loadHistory(), and saveHistory(), and that the three functions are gone.
Step 14 — Build and check the behavior
- Press ⌘B. The build should finish with no errors and no warnings.
- Press ⌘R and roll a few times with different quantities and modifiers.
- Confirm that the result card, the history, and the Haptic feedback toggle behave as they did in Chapter 11.
- Check the Stepper limits. Quantity stops at 10 and at 1. The modifier stops at +20 and at -20.
If the app behaves the same, the refactor succeeded. If it does not, go to Troubleshooting before going further, because the tests you write next depend on this code being correct.
Part D — Create the test target
Xcode keeps tests in a separate target, so the code you ship does not contain them. You create the target once, and then add files to it.
Step 15 — Create the test target
- Choose File → New → Target… (wording may differ slightly in your Xcode version).
- Under the iOS section, choose Unit Testing Bundle, then click Next.
- Set the product name to
DiceFoundryTests. - Confirm that Target to be Tested is
DiceFoundry. This tells Xcode that the tests load your app's code. - Set the Testing System to Swift Testing. Leave the language as Swift.
- Click Finish. If Xcode asks whether to activate the new scheme, choose Activate.
Xcode now has a second target and a DiceFoundryTests folder in the Project navigator. Its build settings are not part of this chapter, and you do not need to change them.
The Testing System option is the one that decides the framework for every file in the target. Swift Testing uses @Test and #expect, which is what this chapter teaches. If you choose XCTest by mistake, the files in this chapter will not compile, and you should delete the target and create it again.
Step 16 — Delete the sample test file
Xcode creates a sample test file in the new folder, normally named after the target, such as DiceFoundryTests.swift. It contains a placeholder test that does not check anything useful. Delete it so your folder contains only the three files you will add.
File: DiceFoundryTests/DiceFoundryTests.swift (the template file Xcode created; the exact name may differ) · Where: the DiceFoundryTests folder · Action: Delete
Right-click the file, choose Move to Trash, and confirm. Moving to the Trash is reversible. You do not need to empty the Trash.
Part E — Write the three test files
Each test file goes in the DiceFoundryTests folder. Before you type each file, make sure its target membership is correct.
A test file in the app target fails, because the app target cannot import itself with @testable. A message similar to No such module 'DiceFoundry' or Cannot find 'DiceRoller' in scope in a test file usually means the file is not in the DiceFoundryTests target. Select the file and open the File inspector (⌥⌘1). Under Target Membership, check DiceFoundryTests and make sure DiceFoundry is unchecked. If the folder syncs automatically to the target in your Xcode version, there may be no checkboxes; then check the file's location in the folder instead.
Step 17 — Create DiceRollerTests.swift
File: DiceFoundryTests/DiceRollerTests.swift (new) · Where: a new file in the DiceFoundryTests folder, with only the DiceFoundryTests target checked · Action: Create file
Type the file in the order below. The blank lines are optional, and Xcode's generated header comment may differ from the listing; keep it if it is there. The first block begins the type:
//
// DiceRollerTests.swift
// DiceFoundryTests
//
import Testing
@testable import DiceFoundry
@MainActor
struct DiceRollerTests {
The first test checks that the roller uses the values it is given:
@Test func rollUsesInjectedValues() {
let roller = DiceRoller(randomValue: { _ in 4 })
let roll = roller.roll(.d6, quantity: 3, modifier: 0)
#expect(roll.values == [4, 4, 4])
}
What it does: creates a roller whose random source always returns 4, rolls three six-sided dice, and checks that every value is 4.
Why it is written this way: this is the test that the injection exists to make possible. Because the random source is predictable, the expected result is exact. The test proves that roll calls the injected function and uses its results, not some other source.
The next test checks the number of dice:
@Test func rollProducesRequestedNumberOfDice() {
let roller = DiceRoller()
for quantity in DiceRoller.quantityRange {
let roll = roller.roll(.d8, quantity: quantity, modifier: 0)
#expect(roll.values.count == quantity)
}
}
What it does: uses the real random source, and checks every quantity in the allowed range, from 1 through 10.
Why it is written this way: it reads the range from DiceRoller.quantityRange rather than writing 1...10 again. If the range changes, the test follows the rule, not a stale copy of it. The test does not check the values, because they are random. It checks only the count, which is predictable.
The next test is a boundary test:
@Test func quantityIsClampedToValidRange() {
let roller = DiceRoller(randomValue: { _ in 1 })
#expect(roller.roll(.d6, quantity: 0, modifier: 0).values.count == 1)
#expect(roller.roll(.d6, quantity: -5, modifier: 0).values.count == 1)
#expect(roller.roll(.d6, quantity: 99, modifier: 0).values.count == 10)
}
What it does: checks the three boundary cases: a quantity below the minimum (0, and a negative number), and a quantity above the maximum (99). Each should be clamped to the nearest end of the range.
Why it is written this way: the most useful tests check the edges. A quantity of 0 is what a broken Stepper could produce, and 99 is what a typed value could produce. Each #expect is one rule, so a failure names the exact case that broke.
The next test checks which range each die asks for:
@Test func rollRequestsTheCorrectRangeForEachDie() {
for dieType in DieType.allCases {
var requestedRange: ClosedRange<Int>?
let roller = DiceRoller(randomValue: { range in
requestedRange = range
return range.lowerBound
})
_ = roller.roll(dieType, quantity: 1, modifier: 0)
#expect(requestedRange == 1...dieType.sides)
}
}
What it does: for each die type, it records the range the roller asked the random source for, and checks that it is 1...sides. A d4 must ask for 1...4, a d20 for 1...20.
Why it is written this way: the closure captures the local variable requestedRange and stores the range it receives. After the roll, the test reads the variable. This is the same closure-capturing behavior described in the Concept Explanation. The _ = before the roll discards the returned RollResult, because this test cares only about the range.
The last test checks the real random source over many rolls:
@Test(arguments: DieType.allCases)
func realRandomValuesStayInRange(dieType: DieType) {
let roller = DiceRoller()
for _ in 1...200 {
let roll = roller.roll(dieType, quantity: 10, modifier: 0)
for value in roll.values {
#expect((1...dieType.sides).contains(value))
}
}
}
}
What it does: for each die type, rolls 10 dice 200 times with the real random source, and checks that each value is within the die's range.
Why it is written this way: a single roll can be right by luck, so the test rolls 2,000 dice per die type. The arguments: line makes Xcode run the function once for each die type, so a failure names the die. (1...dieType.sides).contains(value) asks whether the value is inside the closed range. The closing brace on the last line ends the DiceRollerTests struct.
Every line in these blocks appears in Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/DiceFoundryTests/DiceRollerTests.swift. If you want to compare your file, open that file and check it line by line.
Step 18 — Create RollResultTests.swift
File: DiceFoundryTests/RollResultTests.swift (new) · Where: a new file in the DiceFoundryTests folder, with only the DiceFoundryTests target checked · Action: Create file
//
// RollResultTests.swift
// DiceFoundryTests
//
import Testing
@testable import DiceFoundry
@MainActor
struct RollResultTests {
@Test func courseExampleThreeD6PlusTwo() {
let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
#expect(roll.subtotal == 12)
#expect(roll.total == 14)
#expect(roll.notation == "3D6 + 2")
#expect(roll.valuesDescription == "4, 2, 6")
}
What it does: checks the worked example from the course specification against the model. The dice are 4, 2, and 6, and the modifier is +2. The subtotal is 12, the total is 14, and the text fields read 3D6 + 2 and 4, 2, 6.
Why it is written this way: this test uses the exact numbers from the specification. If you ever read a test named after a real example, you know which requirement it protects, and you can check it against the paper. A test for the total would be useless if it used random values; here the values are fixed because the model does not roll anything.
@Test func negativeModifier() {
let roll = RollResult(dieType: .d20, values: [15, 3], modifier: -4)
#expect(roll.total == 14)
#expect(roll.notation == "2D20 - 4")
}
@Test func zeroModifierHasNoSuffix() {
let roll = RollResult(dieType: .d8, values: [5], modifier: 0)
#expect(roll.total == 5)
#expect(roll.notation == "1D8")
}
@Test func modifierFormatting() {
#expect(RollResult.formatModifier(3) == "+3")
#expect(RollResult.formatModifier(0) == "0")
#expect(RollResult.formatModifier(-2) == "-2")
}
}
What it does: checks the negative-modifier case (where the total must subtract), the zero-modifier case (where no suffix appears), and the three sign cases of formatModifier. The closing brace ends the struct.
Why it is written this way: each test covers one branch of the logic. The if modifier > 0, else if modifier < 0, and else branches in notation each have a test, and the three switch cases of formatModifier each have an #expect. A branch with no test is a branch you have not verified.
Step 19 — Create HistoryStoreTests.swift
File: DiceFoundryTests/HistoryStoreTests.swift (new) · Where: a new file in the DiceFoundryTests folder, with only the DiceFoundryTests target checked · Action: Create file
//
// HistoryStoreTests.swift
// DiceFoundryTests
//
import Testing
import Foundation
@testable import DiceFoundry
@MainActor
struct HistoryStoreTests {
// Each test gets its own file in the temporary directory,
// so tests never touch the real roll history.
let store = HistoryStore(
fileURL: URL.temporaryDirectory.appending(path: "history-test-\(UUID().uuidString).json")
)
What it does: gives each test a new HistoryStore that points at a file with a unique name in the temporary folder. UUID().uuidString creates a random identifier, so the file name is different every time.
Why it is written this way: the real history file lives in the app's Documents folder. A test that wrote there would overwrite your roll history. Swift Testing creates a new instance of the test type for each test function, so each test gets its own store and its own file. The line is longer than 90 characters, and it is kept as one line to match the checkpoint.
@Test func missingFileLoadsAsEmptyHistory() throws {
let history = try store.load()
#expect(history.isEmpty)
}
@Test func savedHistoryLoadsBackUnchanged() throws {
let first = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
let second = RollResult(dieType: .d20, values: [11], modifier: -1)
try store.save([first, second])
let loaded = try store.load()
#expect(loaded.count == 2)
#expect(loaded[0].id == first.id)
#expect(loaded[0].values == [4, 2, 6])
#expect(loaded[0].total == 14)
#expect(loaded[1].dieType == .d20)
#expect(loaded[1].modifier == -1)
}
What it does: the first test checks that a missing file loads as an empty list, which is the first-launch case. The second saves two rolls to the file, loads them back, and checks that the identity, values, total, die type, and modifier all survived the round trip through JSON.
Why it is written this way: the round trip is the test that matters for persistence. Saving and loading are separate methods, and each can be wrong in a way that the other hides. Comparing the loaded values with the saved ones catches both. The try keyword appears because save and load can throw, and the test function is marked throws so an unexpected error fails the test.
@Test func corruptFileThrowsAnError() throws {
try Data("not json".utf8).write(to: store.fileURL)
#expect(throws: (any Error).self) {
try store.load()
}
}
}
What it does: writes text that is not JSON to the test file, and checks that loading it throws an error instead of returning a wrong answer.
Why it is written this way: a corrupt file is a real failure case, and the most dangerous behavior would be silently returning an empty history that then overwrites the real file. The test proves that the error is raised so the caller can handle it. The closing brace ends the struct.
Step 20 — Run all the tests
- Press ⌘U. Xcode builds the app and the test target, then runs every test.
- Open the Test navigator with ⌘6 if it does not open by itself. Each test has a status icon.
- Confirm that all tests pass. The Test navigator and the status bar at the top of the window both report the result.
If every test passes, you have confirmed that the roller, the model, and the store follow the rules you wrote down. If a test fails, the Issue navigator and the Test navigator show the expectation that failed, with the values that were compared. Read the failure carefully before you change anything. The Troubleshooting section describes the common failures.
Before this chapter was published, the reference project was built and its tests were run on two simulators, and every test passed. Your count may differ on a different simulator, because the parameterized test reports each die type separately.
Part F — Break the code on purpose
A test that has never failed has not been shown to work. In this part you introduce two logic errors, one at a time, and watch the tests catch them. Then you introduce a persistence error that no unit test can see, and you find it by hand.
Step 21 — Introduce a wrong random range
File: Logic/DiceRoller.swift · Where: inside roll(_:quantity:modifier:), the line that calls randomValue · Action: Replace
Before:
values.append(randomValue(1...dieType.sides))
After (this compiles, and it is wrong):
values.append(randomValue(0...dieType.sides))
What it does: asks the random source for values from 0 through the number of sides. A d6 can now produce a 0, which is not a face of a die.
What should happen: the project builds. Press ⌘U. Two tests fail:
rollRequestsTheCorrectRangeForEachDiefails for every die type, because the range requested is0...sides, not1...sides.realRandomValuesStayInRangefails for the dice types on which a 0 appears in 2,000 rolls, which is nearly all of them.
The test rollUsesInjectedValues still passes, because the fake random source ignores the range and returns 4.
Why it matters: this is the bug class that the rollRequests... test exists to catch. The second failing test shows the same bug from the other side, using the real random source. Two tests checking the same rule from different angles is a good sign. If you wrote 1..<dieType.sides instead, the project would not compile, because randomValue requires a closed range; a message similar to Cannot convert value of type 'Range<Int>' to expected argument type 'ClosedRange<Int>' would appear. That is the compiler catching the same kind of mistake at build time.
Read the failure message. It names the test, the line, and the values compared. Then restore the original line:
File: Logic/DiceRoller.swift · Where: the same line · Action: Replace
values.append(randomValue(1...dieType.sides))
Press ⌘U again, and confirm that every test passes.
Step 22 — Introduce a wrong total
File: Models/RollResult.swift · Where: the computed property total, which currently reads subtotal + modifier · Action: Replace
Before:
subtotal + modifier
After (this compiles, and it is wrong):
subtotal - modifier
What should happen: the project builds. Press ⌘U. Three tests fail:
courseExampleThreeD6PlusTwo, because the total of 12 minus 2 is 10, not 14.negativeModifier, because 18 minus negative 4 is 22, not 14.savedHistoryLoadsBackUnchangedinHistoryStoreTests, because the total of the first loaded roll is not 14.
zeroModifierHasNoSuffix still passes, because subtracting zero changes nothing. That is correct behavior for that test, and it is a useful lesson: a passing test tells you only that the case it checks works.
Why it matters: the worked example from the specification catches this bug in one line. The total is the number the player reads, and the test checks it against a number written by hand. Undo the experiment now:
File: Models/RollResult.swift · Where: the computed property total · Action: Replace
subtotal + modifier
Press ⌘U again, and confirm that every test passes.
Step 23 — Introduce a persistence error no unit test can see
Now the bug is one that the tests cannot reach. clearHistory() lives in ContentView, and it calls history.removeAll() and then saveHistory(). If the save line is missing, the history is cleared on screen but still exists in the file.
File: ContentView.swift · Where: inside clearHistory(), the second line · Action: Delete
Before:
private func clearHistory() {
history.removeAll()
saveHistory()
}
After (the save line is removed):
private func clearHistory() {
history.removeAll()
}
What should happen: the project builds, and ⌘U still passes every test. No test calls clearHistory(), and the stores pass because they never see this function.
Find the bug by hand, using the manual test script:
- Press ⌘R and roll three times, so the history contains three rolls.
- Tap Clear. The history disappears from the screen.
- Stop the app with ⌘. and run it again with ⌘R.
- Look at the history. In the broken version, the three rolls come back.
The rolls come back because the file on disk was never changed by the clear. When the app launched, loadHistory() read the file, which still held the rolls. This is a persistence error, and the reproduction steps show it reliably.
A test of clearHistory() would need the view to be created in a test, or its logic to be moved out of the view. Chapter 13 moves the state and the save logic into a separate view model, which can be tested without a screen. Until then, the manual test script is the right tool for this kind of bug.
Restore the save line:
File: ContentView.swift · Where: inside clearHistory(), after history.removeAll() · Action: Add
saveHistory()
Repeat the manual test from the steps above, and confirm that the history is empty after a relaunch.
Step 24 — Optional: produce a corrupt file on purpose
This step is not a code change, so it has no EDIT callout. It shows the error path that corruptFileThrowsAnError tests, in the running app. Only do it on the Simulator, never on a device that holds data you care about.
- Find the app's data folder in the Simulator. In Terminal, run:
xcrun simctl get_app_container booted com.blackwellfoundry.DiceFoundry data
Use your own bundle identifier if you chose a different one in Chapter 1.
- Open the
Documentsfolder inside the path the command printed. It containsroll-history.json. - Quit the app with ⌘. in Xcode. Replace the contents of
roll-history.jsonwith the textnot json, and save the file. - Run the app with ⌘R. The history is empty, and the debug console shows a message similar to the following.
Could not load roll history: <a decoding error that describes the problem>
Your app now shows an empty history after a corrupt file. loadHistory() prints the error and leaves the history empty, so the app keeps running. This is a deliberate design choice: the error is visible in the console, but a damaged file does not crash the app. Roll a few dice to create a new, valid file. Your app will overwrite the damaged file the next time it saves.
Expected Results
When you finish Part C, the app should look and behave exactly as it did at the end of Chapter 11. Chapter 12 changes how the code is organized, not what the user sees.

After Part D, the Project navigator shows the DiceFoundryTests folder with the test files you created, and the Logic folder in the app. The Test navigator (⌘6) lists each test grouped by its type. The layout looks like this, and it is an illustrative mockup, not a screenshot:
Illustrative mockup — not a screenshot
Test navigator (⌘6)
▾ DiceFoundryTests
▾ DiceRollerTests
pass rollUsesInjectedValues
pass rollProducesRequestedNumberOfDice
pass quantityIsClampedToValidRange
pass rollRequestsTheCorrectRangeForEachDie
pass realRandomValuesStayInRange(dieType:) d4, d6, d8, d10, d12, d20
▾ HistoryStoreTests
pass missingFileLoadsAsEmptyHistory
pass savedHistoryLoadsBackUnchanged
pass corruptFileThrowsAnError
▾ RollResultTests
pass courseExampleThreeD6PlusTwo
pass negativeModifier
pass zeroModifierHasNoSuffix
pass modifierFormatting
The word pass means that test passed on the last run. A failing test shows a red mark instead, and its expectation appears in the Issue navigator and next to the test in the editor. The exact layout depends on your Xcode version.
When you break the total in Step 22, the expected result is that three tests show red marks, and the failing expectations show the values that were compared. When you break the random range in Step 21, two tests fail. When you forget the save in Step 23, every test still passes, and only the relaunch test reveals the bug. Seeing a test suite pass while the app is wrong is a useful lesson in its own right: tests check what they were written to check.
Finally, the debug console messages from Part B should look similar to the lines below, with your own numbers. The po lines print the description of each value, and p adds the type.
Illustrative mockup — not a screenshot
3
d6
▿ 3 elements
- 0 : 4
- 1 : 2
- 2 : 6
(Int) $R0 = 14
Reading This Like a Developer
This chapter adds a new layer to the flow you have been tracing since Chapter 4. The diagram below shows the roll from the button press to the screen update, with the new roller and the tests in place.
Here is the same flow as text, so you can follow it in the code:
Roll Dice button tapped
-> performRoll() ContentView (presentation)
-> roller.roll(selectedDie, ...) DiceRoller (business rule)
-> clamp quantity min(max(...)) with Self.quantityRange
-> randomValue(1...sides) stored closure: real or injected
-> RollResult(...) model: subtotal, total, notation
-> latestRoll = roll @State, the spinning result view
-> rollCount += 1 @State, drives animation and haptic
-> history.insert(roll, at: 0) @State array
-> saveHistory() HistoryStore.save (writes roll-history.json)
-> SwiftUI sees changed @State re-runs body, updates the screen
Work through the questions below for this chapter's code. They are the same questions you asked in earlier chapters, with a new emphasis on testing.
Where does execution begin? For a roll, it begins at the button's action closure, which calls performRoll(). For a test, it begins at a function marked @Test. Xcode finds those functions and runs them, and no button is involved. A test starts without the app's user interface at all, which is the reason DiceRoller was extracted.
Which code runs when the button is pressed? performRoll() runs. It calls roller.roll, which runs the clamp and then the loop that calls randomValue once for each die. The function then returns a RollResult, and performRoll() stores it. Notice that the random values are produced before any state changes. This order is deliberate. The animation and haptic in Chapter 11 fire after rollCount changes, so they react to a result that already exists.
Which variables hold state? Inside the view, the @State properties hold state: latestRoll, history, rollCount, and the selection controls. DiceRoller holds no state at all. Its two ranges are constants and its randomValue is a function, so calling roll twice with the same arguments does not change the roller. That is what makes it easy to test.
Where does a value originate and where is it modified? The random numbers originate in Int.random(in:), which is reached only through the stored closure. In the app, the values are modified nowhere after roll returns them. The RollResult is immutable: its properties are let. The only thing that changes is the history array, which performRoll() inserts into and trims.
How does data move between views? The roll is created in ContentView and passed to ResultView and HistoryRow as a plain value. Each of those views receives a copy and draws it. Nothing in the child views can change the roll, which is why the history is safe to display.
How does the interface respond to state changes? When latestRoll, history, or rollCount changes, SwiftUI calls ContentView.body again, and only the parts of the screen that depend on the changed value are redrawn. The tests do not involve this step at all. They run without rendering anything, and that is the whole value of separating the rule from the view.
Where is data saved? performRoll() and clearHistory() both call saveHistory(), which calls store.save. HistoryStore writes the JSON file in the Documents folder. This is the step the manual test in Part F checks, because no unit test calls clearHistory().
How are errors handled? Two different strategies appear in this chapter, and the difference matters. DiceRoller.roll does not throw. It clamps out-of-range input so a roll always happens. HistoryStore.load and save do throw, because a file can be missing or damaged, and the caller must decide what to do. ContentView catches the error, prints it with print, and keeps running. The test corruptFileThrowsAnError checks that the store does throw, so the caller has the information it needs.
Which code is business logic and which is presentation logic? This is the most important question for a tested codebase.
- Business logic is the set of rules about dice: the allowed ranges, the clamp, the requested range for each die, how the subtotal and total are calculated, how the notation is written, and how the history is stored. This lives in
DiceRoller,RollResult,DieType, andHistoryStore. The tests in this chapter cover it. - Presentation logic is the set of decisions about the screen: which view shows which value, the layout, the colors, the animation, and the haptic. This lives in
ContentView,ResultView,HistoryRow, and the other views. Chapter 11 styled it, and Chapter 13 will move part of its state and logic into a view model so more of it can be tested.
The user has three rolls, taps Clear, quits the app, and relaunches it. Predict what the history shows in two versions of clearHistory(): (a) the correct version, which runs history.removeAll() and then saveHistory(); (b) the broken version, which runs only history.removeAll(). Explain your answer in terms of which file loadHistory() reads on launch. The answer is in the Prediction Answers section.
When you read a SwiftUI file for the first time, do not follow the layout. Find where each value is created, follow it to where it is stored, and then find where the screen reads it. In this chapter the chain is roll, then latestRoll, then ResultView. A value that is created in one place, stored in another, and displayed in a third is the normal shape of an app's data flow, and it is easier to debug once you can draw it.
Troubleshooting
Most problems in this chapter fall into three groups: the compiler rejects a line, the app behaves differently after the refactor, or a test fails. The entries below follow the same order as the chapter. In each entry, the message is written as a message similar to the one Xcode shows, because Xcode's wording changes between versions.
Cannot find 'reslt' in scope
ContentView.swift:<line>:<column>: error: Cannot find 'reslt' in scope
What it means: the compiler cannot find a name you used. This is the exact error from Part A, Step 1.
Likely causes: a typo in a variable or constant name; a name that was declared inside a different function, so it is not visible where you used it; a function or property that was deleted but is still called. The third cause is common after Part C, Step 13: if you deleted rollDice before rewriting performRoll(), the error names rollDice.
How to investigate: read the name in the message, search the file for it with ⌘F, and check that it is spelled the same way in its declaration. If the name is a function you deleted, check the function that calls it. Fix the first error in the Issue navigator, then build again.
Cannot convert value of type 'Int' to specified type 'String'
Cannot convert value of type 'Int' to specified type 'String'
What it means: you gave a value of one type where the compiler expected another. This is the type-mismatch error from Part A, Step 2.
Likely causes: a number used where text is required; a let or parameter whose declared type does not match the value you assign; a mistaken assumption about what a property holds, such as total being text when it is a whole number.
How to investigate: Option-click the value or the name to see its declared type, or check the declaration of the property. Then decide which side is wrong. If the declared type is correct, convert the value explicitly, for example with String(roll.total). If the value is correct, change the declaration.
Expected '}' in struct
Expected '}' in struct
What it means: the compiler reached the end of a struct and found an opening brace without a matching closing brace. This is the error from Part A, Step 4. Errors such as "Expected '}' at end of file" or errors on the last line of the file can have the same cause.
Likely causes: a closing brace deleted or left out during a copy and paste, often after moving code between functions; an extra opening brace in an if or closure; a function pasted into the wrong place.
How to investigate: do not start at the reported line. Start at the last function you edited and count the braces: each func needs one { and one }, and each if and for inside it needs its own pair. Use ⌃I to re-indent the file, because the indentation will look wrong exactly where the brace is missing.
Cannot assign to property: 'self' is immutable
Cannot assign to property: 'self' is immutable
What it means: code tried to change a stored property of the view struct, and the property is not marked as state. This is the error from Part A, Step 3.
Likely causes: a property used to hold changing data was declared without @State. In SwiftUI, a struct cannot change its own stored properties unless they are marked with a property wrapper such as @State.
How to investigate: find the property named in the line that failed, then check its declaration. Changing data that the screen shows should have @State private var. Data that comes from outside the view should be passed in as a parameter or a @Binding. Chapter 13 covers the second case in more depth.
Type 'RollResult' does not conform to protocol 'Decodable'
A message similar to the following appears when a type inside RollResult cannot be encoded or decoded, usually because DieType lost its Codable conformance:
enum DieType: Int, CaseIterable, Identifiable {
Type 'RollResult' does not conform to protocol 'Decodable'
What it means: RollResult declares that it conforms to Codable, and therefore to Decodable. It cannot, because one of its stored properties, dieType, is not codable. The error names RollResult, but the cause is in DieType.
Likely causes: a type in a Codable structure was edited and lost its conformance; a new property with a type that is not codable was added to RollResult.
How to investigate: find each stored property of RollResult and check its type. Every type used there must conform to Codable. In this project, DieType conforms through its declaration, which should read enum DieType: Int, CaseIterable, Identifiable, Codable. Restore the missing conformance. Note that Int and Date and UUID are already codable.
Tests do not compile: No such module or Cannot find in scope
No such module 'DiceFoundry'
or, in a test file:
Cannot find 'DiceRoller' in scope
What it means: the test file was compiled without access to the app's code. It is usually in the wrong target, or the test target does not depend on the app.
Likely causes: the test file's target membership includes only the app target, or nothing at all; the test target was created without the app as its "Target to be Tested"; the file was created in a folder that Xcode does not associate with the test target.
How to investigate: select the test file, open the File inspector (⌥⌘1), and check the Target Membership boxes. The test file should be checked for DiceFoundryTests only. Then open the test target's settings and confirm that its dependencies include the DiceFoundry app.
A test does not appear in the Test navigator
What it means: Xcode does not see the function as a test, so it will never run.
Likely causes: the function is missing @Test; the function is inside a type that is not struct or class (for example, a function written outside any type); the file is not in the test target, so Xcode never compiles it.
How to investigate: check that the line above each test function reads @Test, and that the test file is in the DiceFoundryTests target as described above. Then press ⌘U again. Xcode builds the test target before it lists the tests.
An expectation failed
Expectation failed: (roll.total → 10) == 14
or a similar message from the test that failed.
What it means: the rule in the test is not satisfied by the code. The message shows the expression that was checked and the values it compared. In this example, the total was 10 when the test expected 14.
Likely causes: a real bug in the code under test (the most common case, and the reason the test exists); a wrong expected value in the test; a test that depends on random values without accounting for them.
How to investigate: read the expression first. Then decide which side is wrong: work the rule out by hand, using the worked example in the specification if you can. If the code is wrong, fix the code and rerun the test. If the test is wrong, fix the expected value and explain why in a comment. Do not change the expected value to match a broken result without working it out. That is how a test becomes useless.
The breakpoint does not stop the app
What it means: the app ran past the line without pausing.
Likely causes: the breakpoint is disabled (its arrow is grey, not blue); the line was never reached, because the Roll Dice button was not tapped, or a different function ran; the breakpoint is on a blank line or a comment; the scheme is set to release, not debug.
How to investigate: confirm the arrow is blue, and tap the button again after the app has started. Check the Product menu and the scheme name at the top of the window. If the line is inside a function that the code never calls, add a breakpoint at a line you know runs.
Thread 1: Fatal error: Index out of range
Thread 1: Fatal error: Index out of range
What it means: code tried to read an array position that does not exist. The app stops with a crash report, which is a runtime error. The message is similar in form to the one shown.
Likely causes: reading values[0] when values is empty; reading a fixed position, such as values[2], from a list that may be shorter; a loop that uses the wrong bounds.
How to investigate: open the Debug navigator (⌘7) or the stack trace shown in the debug area. The first frame that names your code tells you the file and line. Read the line, find out what the array held at that moment, and decide whether the code should check the count first. Chapter 6 introduced isEmpty and count for exactly this kind of check.
The app passes every test, but the history comes back after a relaunch
What it means: this is the persistence error from Part F, Step 23. The tests are green because no test covers clearHistory().
Likely causes: a function that changes stored data without calling the save method; a save that was removed during a refactor; a save that happens in one path but not another.
How to investigate: do not trust the green checks. Use the manual test script: roll, clear, quit, relaunch. Then read every function that changes history and confirm that each one ends with saveHistory(). Chapter 13 explains how moving the logic into a view model lets you test this directly.
Knowledge Check
- For each of the following, name the kind of failure it is (compile-time, runtime, or logic), and say which tool in this chapter would find it first: (a) a misspelled name, (b) a total that is two points too low, (c) an array read at an index that does not exist.
- Why does
DiceRollerread its random source from a stored property rather than callingInt.random(in:)directly insideroll? Explain what a test can do with the property that it cannot do with a direct call. - Read
min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound)for an input of 0 and an input of 99. What is the result in each case, and why do you read the expression from the inside out? - Explain why
quantityIsClampedToValidRangeuses a fake random source that returns 1, whilerealRandomValuesStayInRangeuses the real one. What rule does each test check, and why could one test not do the other's job? - A teammate says, "All the tests pass, so clearing the history is correct." Explain why that conclusion does not follow, and describe the manual test that would show the problem.
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.
Do this challenge on a Git branch so the guided project stays identical to the reference. Create the branch with git switch -c challenge-12, and switch back to main before you start Chapter 13.
DiceRoller.roll clamps the quantity to DiceRoller.quantityRange, but it passes the modifier through unchanged. The Stepper prevents out-of-range modifiers in the interface, but a roll created in code, or a value loaded from an edited file, could still carry one. Make roll clamp the modifier to DiceRoller.modifierRange the same way it clamps the quantity, and add a test that proves the behavior.
Acceptance criteria: a modifier of 50 becomes 20 in the returned RollResult, and a modifier of -50 becomes -20; a modifier of 7 stays 7; the existing tests still pass; the project builds with 0 errors and 0 warnings; the new test lives in DiceRollerTests.swift and is named by the rule it checks.
The hints for this challenge are in the Chapter 12 Exercises document, and a complete solution is in the Chapter 12 Answer Key. Try the challenge for a while before you open a hint.
Chapter Completion Checklist
- You have made each of the four Part A experiments, read the first error, and restored the original line.
- You have set a breakpoint, paused the app on Roll Dice, and inspected
roll.valuesandroll.totalwithpoandp. Logic/DiceRoller.swiftexists and contains the ranges,randomValue, androll.RollOptionsViewreads its ranges fromDiceRoller, andContentViewhas arollerproperty.performRoll()calls the roller, androllDie,rollDice, andisValidQuantityare gone fromContentView.swift.- The app behaves as it did at the end of Chapter 11.
- The
DiceFoundryTeststarget exists, uses Swift Testing, and contains no template test file. DiceRollerTests.swift,RollResultTests.swift, andHistoryStoreTests.swiftare in the test target only.- ⌘U runs all tests, and every test passes.
- You have broken the random range and the total, watched the tests fail, and restored both lines.
- You have found the missing save in
clearHistory()with the manual test, and restored it. - You can explain the difference between compile-time, runtime, and logic errors, and name a tool for each.
- You can explain why
DiceRollertakes its random source as a stored closure. - The project builds with no errors and no warnings.
Development Checkpoint
Commit this chapter's work and tag it.
In Xcode: choose Integrate → Commit..., check that the changed files include Logic/DiceRoller.swift, RollOptionsView.swift, ContentView.swift, and the three test files, enter the message Chapter 12: Debugging and testing, and commit.
In Terminal (from your project folder, the one that contains DiceFoundry.xcodeproj):
git add -A
git commit -m "Chapter 12: Debugging and testing"
git tag chapter-12
Before you commit, run git status. It should list the new files and the modified files, and it should not list anything from your breakpoint experiments, because breakpoints are not part of the source.
Compare with the reference: open Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/ in Finder. Compare your files with the reference, for example with:
diff -r path/to/YourProject/DiceFoundry path/to/Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/DiceFoundry
diff -r path/to/YourProject/DiceFoundryTests path/to/Reference-Checkpoints/Checkpoint-12-Debugging-and-Testing/DiceFoundryTests
Expect differences only in the header comments Xcode generated, in whitespace, and in the wrapped lines you chose to keep. The DiceFoundry folder should differ from the reference only by the SwiftPractice.swift file if you kept it. The test folder should match the reference, apart from any template file you did not delete.
Prediction Answers
Trace the clamp. DiceRoller(randomValue: { _ in 5 }) with roll(.d4, quantity: 100, modifier: -3).
- The result contains 10 values. The quantity of 100 is clamped to the upper bound of
DiceRoller.quantityRange, which is 10. - The first value is 5. The injected function ignores its range and always returns 5, so every value is 5.
- The
subtotalis 50, which is ten 5s added together. Thetotalis 47, because the modifier of -3 is added to the subtotal.
The example shows that the roller does not validate the random source. The test is checking the rules around it, and a fake source that returns an impossible value is still a valid input to those rules.
Before and after the step over. In Part B, Step 8, latestRoll holds the roll from the previous tap, or the last saved roll if the app has just launched. On the very first roll of a fresh launch, it may be the most recent roll from the saved history, or nil if the history is empty. After the line latestRoll = roll runs, latestRoll refers to the roll you just made, which is the same value as the local roll. The Variables view shows that change, which is the reason to watch the values rather than guess them.
The save line after a clear. In version (a), the clear is saved, so the file on disk holds an empty list. On relaunch, loadHistory() reads that empty list and the history is empty. In version (b), the file still holds the three rolls, because nothing wrote the cleared state to it. On relaunch, loadHistory() reads the three rolls, and they come back. The screen looked cleared in both versions, and only the file shows the difference. That is why the relaunch test is the one that finds this bug.