Dice Foundry Solutions and Answer Key

Chapter 7 Answers — Conditional Logic and Modifiers

Knowledge Check Answers

1. What is the value of !(3 > 2) || (5 == 5 && 1 > 4)?

false. Work from the inside out. 3 > 2 is true, so !(3 > 2) is false. Because the left side of || is false, Swift must evaluate the right side (no short-circuit on the ||). On the right, 5 == 5 is true, so the && must also evaluate 1 > 4, which is false; true && false is false. Finally false || false is false. Short-circuiting did not skip anything in this expression; it would have if the left side of || had been true or the left side of && had been false.

2. Why does Swift insist on default: in formattedModifier, and what goes wrong with case 0...:?

A Swift switch must be exhaustive: every possible value of the subject must match some case. An Int can be negative, and neither case 0: nor case 1...: matches negative numbers, so without default: the code does not compile. With case 0...: the code still compiles, but zero is matched by whichever of case 0: and case 0...: comes first. With case 0: first, the output is unchanged but the range overlaps confusingly; if the order were reversed, zero would display as "+0". Writing case 1...: makes the cases non-overlapping and the intent obvious.

3. Why check isValidQuantity(quantity) when the Stepper already limits the value?

Any two of these: (a) The value may arrive some other way in future (restored from a file, passed from another view, set in a test, or the Stepper replaced by a text field). (b) rollDice would crash on a quantity of 0 because 1...0 is an invalid range, so the check sits in front of the operation that would fail. (c) Defense in depth: the outer control can be misconfigured (someone edits the Stepper range to 0...10) and the inner check still holds. (d) A named check documents the business rule in code.

4. Why is computing the heading from the controls a bug, and what fixes it?

The heading would depend on quantity, selectedDie and modifier, which are control state describing the next roll. SwiftUI re-evaluates body whenever state it reads changes, so tapping a stepper or a die button after rolling would rewrite the description of a roll that has not changed. The fix is to record snapshot state at the moment of rolling (rolledModifier, rolledNotation, alongside results) inside performRoll(), and have the result area read only that snapshot state.

5. Values for "2D20 - 4" with dice 15 and 7.

Name Type Value
results [Int] [15, 7]
subtotal Int (computed) 22
rolledModifier Int -4
total Int (computed) 18
rolledNotation String "2D20 - 4"

Challenge Solutions

Challenge 1 — Rate the total

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Reference solution folder: challenge-solutions/ch07-total-rating/.

File: ContentView.swift. Where: inside struct ContentView, for example between formattedModifier and notation. Action: Add.

Example — not part of the Dice Foundry project
    func rating(for value: Int) -> String {
        switch value {
        case ..<1:
            return "Ouch"
        case 1...5:
            return "Low"
        case 6...14:
            return "Solid"
        default:
            return "High"
        }
    }

File: ContentView.swift. Where: inside body, in the else block of if results.isEmpty, after the closing brace of if rolledModifier != 0 { ... }. Action: Add.

Example — not part of the Dice Foundry project
                Text(rating(for: total))
                    .font(.headline)
                    .foregroundStyle(.orange)

Why it works. total is computed from results and rolledModifier, both snapshot state, so the rating describes the roll that happened. The switch checks cases top to bottom: ..<1 is "everything below 1", which is "0 or less" for integers; 1...5 and 6...14 are closed ranges; default catches 15 and above and satisfies the exhaustiveness rule. Placing the Text inside the else block means it exists only after a roll.

Alternatives. case ...0: is equivalent to case ..<1:. You could write case 15...: for the last group and still need a default (it would never run, but the compiler cannot prove that the four ranges cover every integer, so it insists). An if / else if chain works too, but the challenge asked for switch, which reads more like the specification table. A common mistake is Text(rating(for: subtotal + modifier)), which reintroduces the chapter's bug.

Challenge 2 — Natural 20 and natural 1

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Reference solution folder: challenge-solutions/ch07-natural-twenty/.

File: ContentView.swift. Where: below @State private var rolledNotation: String = "". Action: Add.

Example — not part of the Dice Foundry project
    @State private var rolledDie: DieType = .d6

Where: inside performRoll(), in the valid branch, directly after rolledModifier = modifier. Action: Add.

Example — not part of the Dice Foundry project
            rolledDie = selectedDie

Where: inside body, in the else block of if results.isEmpty, after the closing brace of if rolledModifier != 0 { ... }. Action: Add.

Example — not part of the Dice Foundry project
                if results.count == 1 && rolledDie == .d20 {
                    if results[0] == 20 {
                        Text("Natural 20!")
                            .font(.headline)
                            .foregroundStyle(.green)
                    } else if results[0] == 1 {
                        Text("Natural 1")
                            .font(.headline)
                            .foregroundStyle(.red)
                    }
                }

Why it works. rolledDie is a third snapshot value, set in the same place and at the same moment as the others, so it always agrees with results. The outer condition requires both "exactly one die" and "that die was a D20" (&&). Because results.count == 1 is checked first and && short-circuits, results[0] is only read when the array has an element (and inside the outer if the count is already known to be 1). The inner if / else if has no else, so for 2 to 19 no view is produced at all.

Alternatives. A switch results[0] { case 20: ... case 1: ... default: EmptyView() } also works; EmptyView() is SwiftUI's "no view" and has not been taught yet, which is why the if form is preferred here. Using selectedDie == .d20 instead of rolledDie compiles and seems to work, but fails the last two acceptance criteria. Notice how this challenge adds yet another separate variable to describe one roll: that is exactly the pressure that Chapter 8's RollResult structure relieves.

Practice Exercise Answers

A — Predict the output

-25 too low
-1 penalty
0 none
1 bonus
20 bonus
21 too high

..<(-20) matches numbers below -20; -20...(-1) includes both ends; the parentheses around negative numbers keep the range operators from being misread. 21 matches no range and falls to default.

B — Spot the bug

Two bugs. A zero modifier produces "3D6 + 0" because >= 0 sends zero into the positive branch; standard notation omits a zero modifier. A negative modifier produces "2D20 - -4" because the negative branch interpolates modifier (which is -4) after a minus sign. The fix is the chapter's version: test modifier > 0, then else if modifier < 0 using abs(modifier), then else returning dice alone. Fixing the zero case genuinely requires a third outcome, so a third branch is unavoidable.

C — Rewrite with if

Example — not part of the Dice Foundry project
func formattedModifier(_ value: Int) -> String {
    if value > 0 {
        return "+\(value)"
    } else if value < 0 {
        return "\(value)"
    } else {
        return "0"
    }
}
Example — not part of the Dice Foundry project
func notation(quantity: Int, dieType: DieType, modifier: Int) -> String {
    let dice = "\(quantity)\(dieType.name)"
    switch modifier {
    case 1...:
        return "\(dice) + \(modifier)"
    case ..<0:
        return "\(dice) - \(abs(modifier))"
    default:
        return dice
    }
}

Both pairs are correct. Most readers find the switch slightly clearer when the cases are ranges of one value, and the if chain clearer when the conditions are simple comparisons. There is no wrong answer; the point is to recognize that the two forms are interchangeable and choose deliberately.

D — Short-circuit thinking

  1. Safe. If the array is empty, !results.isEmpty is false and && skips the index.
  2. Crashes on an empty array. The index is evaluated first, before the emptiness check, and reading index 0 of an empty array is a runtime error ("Index out of range").
  3. Safe. If the array is empty, results.isEmpty is true and || skips the index.
  4. Safe. If the count is not 1, the index is skipped; if it is 1, index 0 exists.