Chapter 12 Answers — Debugging and Testing
Knowledge Check Answers
1. Kinds of failure.
(a) A misspelled name is a compile-time error. The compiler refuses to build and the Issue navigator shows the first message; fix the first error in the list.
(b) A total that is two points too low is a logic error. The project builds and runs without a crash, so only a check against an expected value finds it. The courseExampleThreeD6PlusTwo test does this.
(c) An array read at a position that does not exist is a runtime error. The app crashes with a fatal-error message while running, and the Debug navigator's stack trace shows the first frame in your code.
2. Why a stored closure. A direct call to Int.random(in:) inside roll always uses the real random generator, so the output cannot be predicted. Because randomValue is a stored property with a default, a test can replace it with a function that returns a fixed value, such as { _ in 4 }. The test then knows exactly what roll should return. The default still uses the real generator, so the app's behavior does not change.
3. min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound). Read from the inside out. For an input of 0, max(0, 1) gives 1, and min(1, 10) gives 1. For an input of 99, max(99, 1) gives 99, and min(99, 10) gives 10. The inner call raises a value that is too low, and the outer call lowers a value that is too high, so the result is always inside the range. Reading inside out matches the order in which the calls are evaluated.
4. Fake versus real random source. quantityIsClampedToValidRange checks the count rule: a quantity of 0 or -5 must become 1, and 99 must become 10. The count does not depend on the values, so a fake source that always returns 1 is enough and keeps the expected results exact. realRandomValuesStayInRange checks the range rule: every value produced by the real generator must lie within the die's faces. A fake source cannot check that, because it would only prove that the fake returns what it was told to return. Each test needs the source that matches the rule it checks.
5. "All tests pass, so clearing is correct." This does not follow. No test calls clearHistory(), because it lives in ContentView, and the tests cover DiceRoller, RollResult, and HistoryStore only. A green suite shows only that the tested rules hold. The manual test is: roll three times, tap Clear, stop the app with ⌘., run it again with ⌘R, and check whether the three rolls return. In the broken version they do, because the file on disk was never changed by the clear.
Independent Challenge Solutions
Challenge 1 — Clamp the modifier as well as the quantity
Solution folder: challenge-solutions/ch12-clamp-modifier/
Verification: Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The verifier run printed:
ch12-clamp-modifier (Swift 5.0): OK errors=0 warnings=0 test cases passed=36 failed=0 (both simulators)
The reference Checkpoint 12 has 34 passing test results: 11 tests that run once on each of the two simulators (22), plus a parameterized test that runs six times on each simulator (12). The challenge adds one test, modifierIsClampedToValidRange(), which runs once on each simulator, giving 36.
Where the change goes:
DiceFoundry/Logic/DiceRoller.swift, insideroll(_:quantity:modifier:), add one line after the quantity clamp:
let safeModifier = min(max(modifier, Self.modifierRange.lowerBound), Self.modifierRange.upperBound)
- The same function, the last line, now passes the clamped value:
return RollResult(dieType: dieType, values: values, modifier: safeModifier)
DiceFoundryTests/DiceRollerTests.swift, a new test placed beforerollRequestsTheCorrectRangeForEachDie:
@Test func modifierIsClampedToValidRange() {
let roller = DiceRoller(randomValue: { _ in 1 })
#expect(roller.roll(.d6, quantity: 1, modifier: 50).modifier == 20)
#expect(roller.roll(.d6, quantity: 1, modifier: -50).modifier == -20)
#expect(roller.roll(.d6, quantity: 1, modifier: 7).modifier == 7)
}
Why it works: the clamp uses the same pattern as the quantity clamp, with Self.modifierRange in place of Self.quantityRange. The min and max calls keep the modifier between -20 and 20, and the passed-in value is no longer used directly. The test uses a fake random source, because the modifier does not depend on the dice values, and it checks both ends and a value inside the range.
Alternatives:
- You could add a
guard-style check in the view that stops out-of-range modifiers from being rolled. That moves the rule into the interface, where it cannot be tested without a screen, so the clamp inDiceRolleris the better place. - You could throw an error for an out-of-range modifier instead of clamping. That is a valid design, but it changes
rollto a throwing function, and every caller must handle the error. For a Stepper-driven app, clamping is simpler.
Test it to prove it: delete the safeModifier line temporarily, change the return to modifier: modifier, and press ⌘U. modifierIsClampedToValidRange should fail. Restore the clamp afterwards.
Extra Exercise Answers
Exercise A — Predict the output. The clamp runs first, so a quantity of 0 becomes 1. The fake source returns range.upperBound, which for a d20 is 20. values is [20], subtotal is 20, and total is 20 + (-20) = 0. If the quantity had been 4, values would be [20, 20, 20, 20], and total would be 80 - 20 = 60.
Exercise B — The test that cannot fail. roll.values.count == roll.values.count compares a value with itself, so it is always true for any value, and the test can never fail. It checks nothing about the roll. A rule-based replacement is #expect(roll.values.count == 2), which checks the quantity rule. It fails if roller.roll stops producing one value per die. Any assertion should be able to fail for a specific wrong behavior.
Exercise C — Boundary check on the die sizes. A suitable test is:
@Test(arguments: DieType.allCases)
func dieSidesMatchRawValues(dieType: DieType) {
#expect(dieType.sides == dieType.rawValue)
}
Changing sides to return rawValue + 1 makes this test fail for each die type, because sides no longer equals rawValue. The prediction is correct only if the test was written with sides compared to rawValue. A test that checked only that sides is positive would not catch the change.
Exercise D — Breakpoint investigation. After the sixth roll, save receives an array of six RollResult values, so history.count is 6. The array can reach 51 entries only if more than 50 rolls are made without a clear, and the trimming line prevents it: in performRoll(), if history.count > HistoryStore.maximumCount { history.removeLast() } removes the oldest entry whenever the count goes above 50, which keeps the array at 50 or fewer.