Dice Foundry Student Workbook

Chapter 7 — Conditional Logic and Modifiers

At the end of Chapter 6, Dice Foundry can roll up to ten dice of any type and add them together. Real tabletop games rarely stop there. A character sheet says "roll 3D6 + 2" or "roll 2D20 - 4": roll some dice, add them up, then add or subtract a fixed number called a modifier. In this chapter you add a modifier control, display the roll in standard dice notation, and show the dice, the subtotal, the modifier and the final total as separate, clearly labeled values. To do that, your code has to start making decisions: is the modifier positive, negative or zero? Has the user rolled anything yet? Is the quantity within the allowed range? That is conditional logic, and it is the main subject of this chapter. You will also find and fix a real design bug, one that AI-generated code makes all the time: a result that quietly changes after the roll because it is computed from the controls instead of from what was actually rolled.

Learning Objectives

By the end of this chapter you will be able to:

  • Write Boolean expressions and combine them with the logical operators &&, || and !.
  • Use if, else if and else to choose between several paths, and explain why the order of the conditions matters.
  • Use switch with single values, closed ranges, one-sided ranges such as 1..., and a default case, and explain why Swift requires a switch to be exhaustive.
  • Validate input against numeric bounds, and explain why the app checks the quantity even though the Stepper already limits it.
  • Show and hide parts of a SwiftUI interface with if and if/else inside body.
  • Format positive, negative and zero numbers for display, including use of abs.
  • Read and produce standard dice notation such as 3D6 + 2, 2D20 - 4 and 1D8.
  • Explain the difference between the individual dice results, their subtotal, the modifier and the final total, and where each one lives in Swift.
  • Explain why a displayed result must describe the roll that happened rather than the current state of the controls, and fix code that gets this wrong.

Concept Explanation

Programs that decide

Every line of Swift you have written so far runs in the same order every time. rollDice(count:sides:) loops, sum(of:) adds, the button assigns. Real programs constantly choose between alternatives: show a placeholder or show a result; write "+2" or "-4"; accept the input or reject it. Code that chooses is called conditional logic, and the thing it chooses on is a condition: an expression whose value is either true or false.

You met the type that holds true or false in Chapter 2: Bool. You also met the comparison operators that produce Booleans:

Expression Meaning Example result when modifier is 2
modifier == 0 equal to false
modifier != 0 not equal to true
modifier > 0 greater than true
modifier < 0 less than false
modifier >= 1 greater than or equal to true
modifier <= 10 less than or equal to true

Any expression that produces a Bool is a Boolean expression. A Boolean expression can be a comparison (quantity > 10), a property that is already a Bool (results.isEmpty), a function that returns Bool (isValidQuantity(quantity)), or several of these combined with logical operators.

Logical operators: &&, || and !

Swift has three logical operators. They take Booleans and produce a Boolean.

Operator Name Result is true when... Example
&& AND both sides are true value >= 1 && value <= 10
\|\| OR at least one side is true value < 1 \|\| value > 10
! NOT the value after it is false !results.isEmpty

A truth table shows every combination:

 a      b      a && b   a || b   !a
 true   true   true     true     false
 true   false  false    true     false
 false  true   false    true     true
 false  false  false    false    true

Two details matter in practice.

Short-circuit evaluation. Swift evaluates the left side first and stops as soon as the answer is known. In a && b, if a is false the whole expression must be false, so b is never evaluated. In a || b, if a is true the answer is true and b is skipped. This lets you write a safe check before a risky one, for example !results.isEmpty && results[0] == 20: if the array is empty, the index is never touched, so the app cannot crash on results[0].

AND and OR are mirror images. "The quantity is valid" is value >= 1 && value <= 10. "The quantity is invalid" is value < 1 || value > 10. Each is exactly the ! of the other. When you flip a condition, every comparison flips and every && becomes || (and the reverse). Getting this wrong is one of the most common logic errors in any language: value >= 1 || value <= 10 looks reasonable, compiles without complaint, and is true for every integer that exists.

Infrastructure Analogy: You already write these

Firewall rules, monitoring alerts and shell scripts are full of Boolean logic. "Alert when CPU > 90 AND it has been high for 5 minutes" is &&. "Page someone when the primary is down OR replication lag exceeds 30 seconds" is ||. Shell's [ -f file ] && echo found even uses the same short-circuit behavior: the second command runs only if the first succeeds.

if, else if and else

An if statement runs a block of code only when its condition is true:

Example — not part of the Dice Foundry project
if modifier != 0 {
    print("There is a modifier")
}

Add else to provide a block that runs when the condition is false. Exactly one of the two blocks runs:

Example — not part of the Dice Foundry project
if results.isEmpty {
    print("Nothing rolled yet")
} else {
    print("Rolled \(results.count) dice")
}

When there are more than two possibilities, chain conditions with else if. Swift checks each condition from top to bottom and runs the first block whose condition is true; it skips everything after that. The final else catches anything that matched none of the conditions.

Example — not part of the Dice Foundry project
if modifier > 0 {
    print("bonus")
} else if modifier < 0 {
    print("penalty")
} else {
    print("no modifier")
}

Because only the first match runs, order matters whenever conditions overlap. In the example above they do not overlap (a number cannot be both greater and less than zero), so the order is a matter of readability. Compare this:

Example — not part of the Dice Foundry project
if total >= 10 {
    print("good")
} else if total >= 18 {
    print("excellent")   // never runs: 18 or more already matched ">= 10"
}

A total of 19 prints "good", because the first condition already matched. When conditions overlap, put the most specific one first.

Swift's if has one rule that catches people coming from other languages: the condition must be a real Bool. There is no "truthy" value. if results.count { } is an error; you must write if results.count > 0 { } or, better, if !results.isEmpty { }. The braces are also required, even around a single line.

switch: choosing by value

When you are choosing among several possibilities based on a single value, a switch statement is often clearer than a chain of if/else if:

Example — not part of the Dice Foundry project
switch selectedDie {
case .d4:
    print("Tetrahedron")
case .d6:
    print("Cube")
default:
    print("Something else")
}

Swift compares the value after switch with each case in order and runs the first one that matches. Several things are different from switch in C, Java or JavaScript, and they all make Swift's version safer:

  • No fallthrough. When a case's code finishes, the switch is done. You do not write break at the end of each case.
  • Exhaustive. Every possible value must be handled by some case. If the compiler cannot prove that, you get an error. For an Int, which has billions of possible values, that almost always means a default case at the end. For an enum such as DieType, listing every case is enough, and the compiler will tell you if you later add a case and forget to handle it. That is a strong reason to prefer switch over if chains for enums.
  • Cases can match more than single values. A case can list several values (case 4, 6, 8:), or a range.

Range cases are what make switch useful for numbers:

Case pattern Matches
case 0: exactly 0
case 1, 2, 3: 1, 2 or 3
case 1...5: 1 through 5, including both ends (closed range)
case 1..<5: 1 through 4 (half-open range, excludes 5)
case 1...: 1 and every number above it (one-sided range)
case ..<0: every number below 0 (one-sided range)
case ...(-1): every number up to and including -1
default: anything not matched above

You built closed ranges such as 1...sides in Chapter 4 and half-open ranges such as 0..<count in Chapter 6. A one-sided range simply leaves one end open: 1... means "from 1 upward, with no upper limit". You cannot loop over 1... (it would never end), but you can ask whether a number is in it, which is exactly what a switch case does.

Infrastructure Analogy: The shell's `case` statement

If you have written case "$1" in start) ... ;; stop) ... ;; *) echo usage ;; esac in a shell script, you already know the shape of a switch. The *) pattern is Swift's default:. The differences: Swift needs no ;; because it never falls through, and Swift refuses to compile if there is any value you forgot to handle.

When to use if and when to use switch

Both statements can express the same decisions. Choose the one that reads most naturally:

  • Use if for one or two conditions, especially when they test different things (isValidQuantity(quantity), results.isEmpty).
  • Use if/else if/else for a short sequence of tests, such as positive, negative, zero.
  • Use switch when you branch on one value into several outcomes, when ranges describe the outcomes, or whenever the value is an enum.

In this chapter you will use both for the same kind of problem (the sign of the modifier), deliberately, so you can compare them.

Input validation and numeric bounds

Validation means checking that a value is acceptable before you act on it. Dice Foundry has two numeric inputs, and each has bounds, a minimum and a maximum:

Input Bounds Why
Number of dice (quantity) 1 to 10 Zero dice is meaningless; rollDice(count: 0, ...) would even crash, because 1...0 is an invalid range. More than ten would not fit the design.
Modifier (modifier) -20 to 20 Large enough for any common game, small enough to keep the display tidy.

The Stepper you met in Chapter 6 enforces bounds itself: in: 1...10 means its minus button stops working at 1 and its plus button stops at 10. So why does this chapter also add an isValidQuantity function that checks the same thing?

Because the Stepper is not the only way a value can arrive. Today it is. In later chapters you will restore state from a saved file, pass values between views, and write tests that call functions directly. Tomorrow someone (or an AI assistant) may replace the Stepper with a text field. A function that would crash on bad input should not rely on every possible caller being well behaved. Checking again right before the risky operation is called defense in depth.

Infrastructure Analogy: Defense in depth

You do not rely only on the perimeter firewall; hosts run their own firewalls too, and a service validates requests even when an API gateway already did. If the outer layer is misconfigured or bypassed, the inner layer still holds. The Stepper range is the perimeter. isValidQuantity is the host firewall in front of rollDice, the function that would actually fail. In Chapter 12 you will strengthen this further by clamping the value inside the roller itself.

Conditional views

In SwiftUI you can use if (and if/else) directly inside body. This does not "hide" a view the way a CSS display: none does; it decides which views exist at all. When the condition changes, SwiftUI re-evaluates body, sees a different set of views, and updates the screen to match.

Example — not part of the Dice Foundry project
if results.isEmpty {
    Text("Tap Roll Dice to begin")
} else {
    Text("\(total)")
}

Before the first roll, results is the empty array, so only the placeholder exists. After a roll, the placeholder is removed and the total appears. You do not write any code to remove the placeholder; you describe what should exist for each state, and SwiftUI reconciles the screen with that description. This is the same declarative idea you met in Chapter 3, now with a decision in it.

This finally fixes something that has been slightly wrong since Chapter 4: before the first roll the app showed a big "0", which looks like a result. With a conditional view, the app can say "Tap Roll Dice to begin" until there is something real to show.

Dice notation

Tabletop games describe rolls with a compact notation:

  3D6 + 2
  │ │   │
  │ │   └── modifier: add 2 to the sum of the dice
  │ └────── die type: a six-sided die ("D" for die, then the number of sides)
  └──────── quantity: roll three of them

Rules for writing it, which the app must follow exactly:

Situation Notation Not
Positive modifier 3D6 + 2 3D6+2, 3D6 + +2
Negative modifier 2D20 - 4 2D20 + -4, 2D20 -4
Zero modifier 1D8 1D8 + 0

Notice the subtle one: for a negative modifier, the notation shows a minus sign followed by the magnitude of the modifier (4, not -4). If you simply inserted the modifier after a plus sign you would get 2D20 + -4. To produce - 4 you need the absolute value of -4, which is 4. Swift's standard library function abs(_:) returns exactly that: abs(-4) is 4, abs(4) is 4, abs(0) is 0.

Formatting signed numbers

There is a second place where the sign matters: the modifier control's label. Here the app shows the modifier on its own, so a positive value needs an explicit plus sign to make it read as a bonus:

Value Display
2 +2
0 0
-4 -4

Swift already writes a minus sign for negative numbers when you interpolate them ("\(-4)" is "-4"), but it never adds a plus sign. So positive numbers need special treatment, zero needs to be left alone (not +0), and negative numbers can use the default. Three cases, chosen by one value, with a range describing one of them: a perfect job for a switch.

Four numbers, not one

A modified roll involves four distinct pieces of information. Keeping them separate is what lets the app explain its own result:

Term Meaning In the worked example
Individual results What each die showed 4, 2, 6
Subtotal Sum of the individual results 12
Modifier Fixed number added afterward +2
Total Subtotal plus modifier 14

Here is how the worked example (one D6 selected, quantity 3, modifier +2, dice showing 4, 2 and 6) is represented in this chapter's Swift code:

Piece Swift Type Value
Die type selectedDie DieType .d6 (whose sides is 6, name is "D6")
Quantity quantity Int 3
Modifier (control) modifier Int 2
Individual results results [Int] [4, 2, 6]
Subtotal subtotal (computed: sum(of: results)) Int 12
Modifier (as rolled) rolledModifier Int 2
Total total (computed: subtotal + rolledModifier) Int 14
Notation rolledNotation String "3D6 + 2"

Two lines in that table may surprise you: why are there two modifiers (modifier and rolledModifier)? That is the design problem in the next section.

The roll must describe what happened

Consider this sequence:

  1. Set the modifier to +2, quantity to 3, die to D6.
  2. Tap Roll Dice. The dice show 4, 2, 6. The app says 3D6 + 2 and 14.
  3. Tap the modifier's plus button once, to +3. Do not roll.

What should the screen say now? The roll that happened was 3D6 + 2 with a total of 14. Nothing was rolled again. The correct display is still 3D6 + 2 and 14.

But suppose the notation and the total were computed from the controls, for example subtotal + modifier. At step 3, modifier becomes 3, SwiftUI re-evaluates body, and the screen now claims 3D6 + 3 with a total of 15, next to the same three dice. Change the quantity to 4 and it claims 4D6 + 3 with only three dice on screen. Select D20 and it claims 4D20 + 3 beside D6 values. The result is lying, and it is lying precisely because SwiftUI is doing its job: the view faithfully reflects the state it depends on, and it depends on the wrong state.

The controls (selectedDie, quantity, modifier) describe the next roll. The result area must describe the last roll. Those are different facts, so they need different storage. The fix is to take a snapshot at the moment of rolling: copy the modifier into rolledModifier and build the notation string into rolledNotation inside the roll function, and have the result area read only the snapshots.

You will build the wrong version first, watch it misbehave, and then fix it. That is deliberate. Once you have seen this bug with your own eyes, you will recognize it in other code.

Infrastructure Analogy: Record the deployment, do not re-read the config

A deployment log entry says "deployed version 4.2 with replicas=3 at 14:05". If your dashboard instead showed "last deployment" by reading the current config file, it would show replicas=5 as soon as someone edited the file, even though nothing was redeployed. The record of an event must capture the inputs as they were at the time of the event. rolledModifier and rolledNotation are that log entry.

This also shows a growing problem. One roll is now described by results, rolledModifier and rolledNotation: three separate variables that must always be updated together. Forget one and they disagree. In Chapter 8 you will replace them with a single value, a RollResult structure, that holds everything about one roll in one place.

Syntax Breakdown

A Boolean expression with &&

Dice Foundry code
        value >= 1 && value <= 10
Token Meaning
value The function's parameter, an Int
>= "Greater than or equal to"; value >= 1 produces a Bool
1 The lower bound
&& Logical AND: true only when both sides are true; the right side is skipped if the left is false
value <= 10 Second comparison: at most the upper bound

Swift evaluates the comparisons before the && (comparison operators have higher precedence than logical operators), so no parentheses are needed. You may add them for readability: (value >= 1) && (value <= 10) means the same thing.

A function that returns Bool, with no argument label

Dice Foundry code
    func isValidQuantity(_ value: Int) -> Bool {
        value >= 1 && value <= 10
    }
Token Meaning
func isValidQuantity Declares a function; the name reads like a yes/no question, a common convention for Bool functions (isEmpty, isValid, hasPrefix)
(_ value: Int) One parameter. _ is the argument label, and underscore means "no label": callers write isValidQuantity(quantity), not isValidQuantity(value: quantity). Inside the function the parameter is named value.
-> Bool Returns true or false
{ value >= 1 && value <= 10 } A single-expression body; its value is returned without writing return (the same rule you used for computed properties)

You used _ in Chapter 6 to ignore a loop variable. Here it plays a related role: it ignores the label. Omitting the label makes sense when the function name already says what the argument is.

if / else

Example — not part of the Dice Foundry project
if condition {
    // runs when condition is true
} else {
    // runs when condition is false
}
Token Meaning
if Keyword that starts a conditional statement
condition Any expression of type Bool; no parentheses required
{ ... } The block to run when the condition is true; braces are mandatory
else Optional; introduces the block that runs otherwise
else if other { Optional, repeatable; tests another condition only if every earlier one was false

switch with ranges

Dice Foundry code
    func formattedModifier(_ value: Int) -> String {
        switch value {
        case 0:
            return "0"
        case 1...:
            return "+\(value)"
        default:
            return "\(value)"
        }
    }
Token Meaning
switch value { Choose a branch based on value
case 0: Matches when value == 0
return "0" Leaves the function with this string; each case returns, so nothing after the switch is needed
case 1...: A one-sided range pattern: matches 1 and every larger integer. The colon after ... ends the case pattern; it is not part of the range.
"+\(value)" A string literal containing a plus sign followed by the interpolated value, for example "+2"
default: Matches everything else. Here "everything else" can only be negative numbers, because 0 and the positives were taken.
"\(value)" Interpolation of a negative number already includes its minus sign, for example "-4"

Note that case labels line up with switch, not indented one level further. That is Swift's standard style, and Xcode's re-indent (⌃I) produces it.

if / else if / else and abs

Dice Foundry code
    func notation(quantity: Int, dieType: DieType, modifier: Int) -> String {
        let dice = "\(quantity)\(dieType.name)"
        if modifier > 0 {
            return "\(dice) + \(modifier)"
        } else if modifier < 0 {
            return "\(dice) - \(abs(modifier))"
        } else {
            return dice
        }
    }
Token Meaning
notation(quantity:dieType:modifier:) Three labeled parameters; the call reads notation(quantity: 3, dieType: .d6, modifier: 2)
let dice = "\(quantity)\(dieType.name)" Builds the shared part, such as "3D6", once, so it is not repeated in every branch
if modifier > 0 { First test: a bonus
"\(dice) + \(modifier)" "3D6 + 2"
else if modifier < 0 { Second test, reached only if the first was false
abs(modifier) The absolute value: abs(-4) is 4. abs is a global function from the Swift standard library; it works on any signed number type.
"\(dice) - \(abs(modifier))" "2D20 - 4"
else { return dice } The only remaining possibility is zero, so the notation is just "1D8"

The else block is necessary: Swift requires every path through a function that returns a String to return one. Without the final else, the compiler would complain that the function could end without returning.

A second Stepper, with a formatted label

Dice Foundry code
            Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)
Token Meaning
Stepper( The same control you used for quantity in Chapter 6
"Modifier: \(formattedModifier(modifier))" The label. Interpolation can contain any expression, including a function call; this one turns 2 into "+2".
value: $modifier The $ gives the Stepper a binding, a two-way connection to the modifier state, so it can both read and change it (full explanation in Chapter 10)
in: -20...20 A closed range with a negative lower bound; the stepper refuses to go outside it

A conditional view inside body

Dice Foundry code
            if results.isEmpty {
                Text("Tap Roll Dice to begin")
                    .foregroundStyle(.secondary)
            } else {
Token Meaning
if results.isEmpty { isEmpty is a Bool property of every array; true before the first roll
Text(...) Exists in the interface only while the condition is true
} else { Everything in the else block exists only after a roll

Inside body, an if produces views rather than running statements. Among the views in body you can put views, if/else, ForEach, and simple local constants such as let label = "Total", but not ordinary statements such as print(...) or assignments like quantity = 3. (The reason is a Swift feature called a result builder, which collects the views; you do not need its details for this course.)

Guided Implementation

You will make every change in ContentView.swift. The order below keeps the project building after every step. Open the project, select ContentView.swift in the Project navigator, and make sure the canvas is showing (⌥⌘↩) if you like to watch the preview.

Step 1 — Add the modifier state

Step 1 — Store the modifier

File: ContentView.swift · Where: inside struct ContentView, directly below @State private var quantity: Int = 1 · Action: Add

Dice Foundry code
    @State private var modifier: Int = 0

What it does. Creates a new piece of view state holding the modifier the user wants to apply to the next roll. It starts at 0, meaning "no modifier".

Why it is written this way. It follows exactly the same pattern as quantity: @State because the value changes while the app runs and the screen must update when it does; private because only this view should change it; an explicit Int type and a sensible default.

What should happen. Build (⌘B). It succeeds. Nothing visible changes yet, because nothing reads modifier.

Step 2 — Write the modifier formatter with switch

Step 2 — Format positive, negative and zero modifiers

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of func sum(of values: [Int]) -> Int · Action: Add

Dice Foundry code
    func formattedModifier(_ value: Int) -> String {
        switch value {
        case 0:
            return "0"
        case 1...:
            return "+\(value)"
        default:
            return "\(value)"
        }
    }

What it does. Converts a number into the text you want to show for a modifier: "+2" for 2, "0" for 0, "-4" for -4.

Why it is written this way.

  • The input is one value and the output depends on which group it falls into: zero, positive, or negative. That is what switch is for.
  • case 0 comes first. Order matters in a switch just as in an if chain; if you wrote case 0...: instead of case 1...:, zero would be caught by the positive case and display as +0.
  • case 1...: uses a one-sided range so you do not have to invent an upper limit. If the modifier range ever grows beyond 20, this code still works.
  • default handles everything left over. The compiler requires it, because an Int switch with only case 0 and case 1... does not cover negative numbers. Swift does not reason "the rest must be negative" on its own; default is how you tell it.
  • The function takes its argument without a label (_ value) because a call such as formattedModifier(modifier) reads naturally.

What should happen. Build (⌘B). It succeeds. The function is not called yet.

Predict Before You Run: Trace the formatter

Without running anything, write down what formattedModifier returns for each of these: formattedModifier(-3), formattedModifier(0), formattedModifier(7), formattedModifier(-20). Then answer: if you swapped the order so that default: came first, what would happen? Answers are at the end of the chapter.

Step 3 — Add the modifier Stepper

Step 3 — Let the user choose a modifier

File: ContentView.swift · Where: inside body, on the line directly below the existing Stepper("Number of dice: ...") · Action: Add the second line shown

Dice Foundry code
            Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
            Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)

The first line is already in your file; it is shown so you can see exactly where the new line goes.

What it does. Adds a second stepper below the quantity stepper. Its plus and minus buttons change modifier between -20 and 20. Its label calls the formatter you wrote in Step 2, so it reads "Modifier: 0", "Modifier: +1", "Modifier: -1".

Why it is written this way. The label is computed from state on every render, so when modifier changes, SwiftUI re-evaluates body, calls formattedModifier again, and the label updates. The range -20...20 is the modifier's numeric bound; the stepper enforces it for you by disabling the minus button at -20 and the plus button at 20.

What should happen. Run (⌘R). Below "Number of dice" you see "Modifier: 0". Tap plus: "+1", "+2". Tap minus several times: "+1", "0", "-1", "-2". Hold the minus button and watch it stop at -20. The modifier does not affect rolls yet.

Step 4 — Add the quantity validator

Step 4 — Validate the quantity

File: ContentView.swift · Where: inside struct ContentView, between the closing brace of sum(of:) and func formattedModifier · Action: Add

Dice Foundry code
    func isValidQuantity(_ value: Int) -> Bool {
        value >= 1 && value <= 10
    }

What it does. Answers one question: is this number an acceptable count of dice? It returns true for 1 through 10 and false for everything else.

Why it is written this way. Both bounds must hold, so the two comparisons are joined with &&. The function has a single job and a name that reads as a question, so the call site will read like English: if isValidQuantity(quantity). The bounds match the Stepper's 1...10. (Having the same numbers in two places is a small maintenance risk; in Chapter 12 you will move them into one named constant.)

What should happen. Build (⌘B). It succeeds.

Predict Before You Run: Bounds

What does isValidQuantity return for 0, 1, 10 and 11? Now imagine a teammate "simplifies" the body to value >= 1 || value <= 10. What does that version return for the same four inputs, and why is it wrong?

Step 5 — Build dice notation with if / else if / else

Step 5 — Produce notation such as "3D6 + 2"

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of formattedModifier · Action: Add

Dice Foundry code
    func notation(quantity: Int, dieType: DieType, modifier: Int) -> String {
        let dice = "\(quantity)\(dieType.name)"
        if modifier > 0 {
            return "\(dice) + \(modifier)"
        } else if modifier < 0 {
            return "\(dice) - \(abs(modifier))"
        } else {
            return dice
        }
    }

What it does. Builds the standard notation string: "3D6 + 2", "2D20 - 4", or "1D8".

Why it is written this way.

  • The shared part ("3D6") is built once into the constant dice and reused by every branch.
  • The three cases are tested with if / else if / else this time, rather than switch, so you can see both forms solving a sign problem. The conditions do not overlap, so their order does not change the result.
  • The negative branch uses abs(modifier) so the output is - 4, not - -4 or + -4.
  • The function takes everything it needs as parameters instead of reading selectedDie, quantity and modifier directly. That makes it a pure function: same inputs, same output, no hidden dependencies. You will see why that matters in Step 10.
  • The parameter named modifier has the same name as the state property modifier. Inside the function, the parameter wins; the name refers to whatever value was passed in.

What should happen. Build (⌘B). It succeeds.

Predict Before You Run: Notation

What string does each call return? notation(quantity: 3, dieType: .d6, modifier: 2), notation(quantity: 2, dieType: .d20, modifier: -4), notation(quantity: 1, dieType: .d8, modifier: 0).

Step 6 — Separate the subtotal from the total

So far total has been the sum of the dice. With a modifier, "the sum of the dice" and "the total" are different numbers, so each needs its own name.

Step 6 — Rename `total` to `subtotal` and add a new `total`

File: ContentView.swift · Where: the computed property var total: Int { sum(of: results) }, above body · Action: Replace

Before:

Example — not part of the Dice Foundry project
    var total: Int {
        sum(of: results)
    }

After (type this for now; you will change one word in Step 11):

Example — not part of the Dice Foundry project
    var subtotal: Int {
        sum(of: results)
    }

    var total: Int {
        subtotal + modifier
    }

What it does. subtotal is now the sum of the individual dice. total is the subtotal plus the modifier. Both are computed properties, so they are recalculated every time they are read.

Why it is written this way. Naming the intermediate value makes it available to the interface, which will show "Dice 12, modifier +2" alongside the total of 14. The existing Text("\(total)") in the circle keeps working without changes, because total still exists; it just means something richer now.

This version has a flaw: total reads the live modifier from the control. Keep it for now. You are going to see the consequences in Step 9.

What should happen. Run (⌘R). Set the modifier to +2 and roll: the big number is the dice sum plus 2. Now tap the modifier's plus button without rolling. Watch the big number. It changes, even though no dice were rolled. Note that, and move on.

Step 7 — Move the roll into performRoll() with validation

The button currently does its work in a single line inside its closure. The roll is about to involve validation and several assignments, so it deserves its own function.

Step 7a — Add a first version of `performRoll()`

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of notation(quantity:dieType:modifier:) (the last function in the struct) · Action: Add (you will extend this function in Step 11)

Example — not part of the Dice Foundry project
    func performRoll() {
        if isValidQuantity(quantity) {
            results = rollDice(count: quantity, sides: selectedDie.sides)
        } else {
            print("Invalid quantity: \(quantity)")
        }
    }

What it does. Checks the quantity before rolling. If it is valid, it rolls and stores the results, exactly as the button did before. If it is not, it prints a message to the Xcode console and leaves the previous result untouched.

Why it is written this way. This is the defense-in-depth check from the Concept Explanation, placed immediately in front of rollDice, which is the function that would crash on a quantity of 0. With the Stepper in place, the else branch cannot run today. It is there for the day the input arrives some other way. print is a deliberately simple way of handling the problem; Chapter 9 offers an optional challenge to show a load-error message. The guided app itself keeps persistence errors in the developer console, a teaching simplification rather than production-ready error handling.

Step 7b — Make the button call `performRoll()`

File: ContentView.swift · Where: inside body, the Button("Roll Dice") closure · Action: Replace the line results = rollDice(count: quantity, sides: selectedDie.sides) so the button reads:

Dice Foundry code
            Button("Roll Dice") {
                performRoll()
            }

What it does. The button's action closure now calls a named function instead of doing the work inline.

Why it is written this way. Short closures in the view keep body about layout. The behavior lives in a function with a name you can search for, read, and later test.

What should happen. Run (⌘R). Rolling works exactly as before.

Step 8 — Show the result conditionally, with notation and a breakdown

Now replace the result area so that it shows a placeholder before the first roll, and the notation, total, dice and modifier breakdown after it. You will also tighten the vertical spacing a little, because the screen now holds one more control and one more line of text.

Step 8a — Reduce the stack spacing

File: ContentView.swift · Where: the first line inside body, currently VStack(spacing: 20) { · Action: Replace with

Dice Foundry code
        VStack(spacing: 16) {
Step 8b — Replace the result area

File: ContentView.swift · Where: inside body, between the first Spacer() (below the steppers) and the second Spacer() (above the Roll Dice button). Select everything from ZStack { down to and including the closing brace of the LazyVGrid(columns: resultColumns, ...). This includes the Text("Rolling \(quantity)\(selectedDie.name)") caption. · Action: Replace with the code below (temporary version; Step 12 changes a few lines)

Example — not part of the Dice Foundry project
            if results.isEmpty {
                Text("Tap Roll Dice to begin")
                    .foregroundStyle(.secondary)
            } else {
                Text(notation(quantity: quantity, dieType: selectedDie, modifier: modifier))
                    .font(.title2)
                    .fontWeight(.semibold)

                ZStack {
                    Circle()
                        .fill(Color.orange.opacity(0.2))
                        .frame(width: 140, height: 140)
                    Text("\(total)")
                        .font(.system(size: 64, weight: .bold))
                }

                LazyVGrid(columns: resultColumns, spacing: 8) {
                    ForEach(results.indices, id: \.self) { index in
                        Text("\(results[index])")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(width: 44, height: 44)
                            .background(Color.orange.opacity(0.2))
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    }
                }

                if modifier != 0 {
                    Text("Dice \(subtotal), modifier \(formattedModifier(modifier))")
                        .foregroundStyle(.secondary)
                }
            }

A practical tip: the circle and the dice grid are the same code you already had, moved one level deeper. Instead of retyping them, you can type the if results.isEmpty { ... } else { lines around the existing code, delete the old caption, add the new Text lines, then select the whole block and press ⌃I to fix the indentation.

What it does.

  • if results.isEmpty shows "Tap Roll Dice to begin" until the first roll. The misleading "0" from earlier chapters is gone.
  • In the else block: a heading with the dice notation, then the total in the circle, then one chip per die.
  • An inner if modifier != 0 adds a breakdown line, "Dice 12, modifier +2", only when there is a modifier to explain. With a zero modifier the subtotal and total are the same number, and the extra line would be noise.
  • The old "Rolling 3D6" caption is removed; the notation heading replaces it.

Why it is written this way. Each conditional describes a state of the interface: nothing rolled; rolled without modifier; rolled with modifier. You never write "remove the placeholder" or "hide the breakdown". When results or modifier changes, SwiftUI re-evaluates body and the right views exist.

What should happen. Run (⌘R). You see "Tap Roll Dice to begin" in the middle of the screen. Set quantity 3, modifier +2, and roll. You see something like 3D6 + 2, a total, three chips, and "Dice 12, modifier +2" (with your own random numbers).

Step 9 — Find the bug

Do not change any code in this step. Run the app and test it like a skeptical user.

Predict Before You Run: Change the controls after a roll

Select D6, set quantity to 3 and modifier to +2, and tap Roll Dice. Suppose the dice show 4, 2 and 6. Write down what the screen shows: notation, total, chips, breakdown line. Now, without rolling again, (a) tap the modifier's plus button once, (b) tap the quantity's plus button once, (c) tap D20. Predict what the notation, total and breakdown show after each tap. Then try it in the simulator and compare.

Look at what you just saw. The dice did not change, but the description of them did. After tapping D20, the app may claim 4D20 + 3 next to three six-sided results. A result display that changes when nobody rolled is wrong, and it would be very confusing in a game ("I rolled 14!" "Your screen says 15.").

The cause is in your code, and you can point to it:

  • Text(notation(quantity: quantity, dieType: selectedDie, modifier: modifier)) reads the three controls.
  • total is subtotal + modifier, which reads the modifier control.
  • if modifier != 0 and formattedModifier(modifier) read the modifier control.

Each of these is "correct" SwiftUI: when state changes, views that read it update. The mistake is in the design: the result area depends on the controls, and the controls describe the next roll, not the last one.

The fix: when the roll happens, record a snapshot of what was rolled, and make the result area read only the snapshot.

Step 10 — Add snapshot state for the rolled values

Step 10 — Store what was actually rolled

File: ContentView.swift · Where: inside struct ContentView, directly below @State private var results: [Int] = [] · Action: Add the two new lines shown

Dice Foundry code
    @State private var results: [Int] = []
    @State private var rolledModifier: Int = 0
    @State private var rolledNotation: String = ""

What it does. Adds two state properties that will hold the modifier and the notation as they were at the moment of the last roll. results already behaves like a snapshot: it is only assigned inside the roll, so it never changes when the controls do.

Why it is written this way. They are @State because the screen displays them and must update when a new roll assigns them. The names start with rolled so that anyone reading the code can tell at a glance which values describe the last roll and which describe the controls. The initial values are never displayed, because the result area only appears once results is not empty.

What should happen. Build (⌘B). It succeeds. Behavior is unchanged until you use them.

Step 11 — Take the snapshot in performRoll()

Step 11a — Record the modifier and notation when rolling

File: ContentView.swift · Where: func performRoll() · Action: Replace the whole function with

Dice Foundry code
    func performRoll() {
        if isValidQuantity(quantity) {
            results = rollDice(count: quantity, sides: selectedDie.sides)
            rolledModifier = modifier
            rolledNotation = notation(quantity: quantity, dieType: selectedDie, modifier: modifier)
        } else {
            print("Invalid quantity: \(quantity)")
        }
    }

What it does. Inside the valid branch, after rolling, it copies the current modifier into rolledModifier and builds the notation from the current controls into rolledNotation. Those three assignments happen together, at the moment of the roll.

Why it is written this way. This is the only place where reading the controls is correct, because this is the moment the controls become a roll. Int and String are copied when assigned, so later changes to modifier do not affect rolledModifier. And because notation(...) is a pure function that takes its inputs as parameters, you can call it once here and store its answer; the stored string will never change on its own.

Step 11b — Base the total on the rolled modifier

File: ContentView.swift · Where: the computed property var total: Int, above body · Action: Replace subtotal + modifier so it reads

Dice Foundry code
    var subtotal: Int {
        sum(of: results)
    }

    var total: Int {
        subtotal + rolledModifier
    }

What it does. The total now combines the dice that were rolled with the modifier that was applied when they were rolled.

Step 12 — Make the result area read only the snapshot

Step 12a — Show the recorded notation

File: ContentView.swift · Where: inside the else block of if results.isEmpty, the first Text · Action: Replace Text(notation(quantity: quantity, dieType: selectedDie, modifier: modifier)) so the heading reads

Dice Foundry code
                Text(rolledNotation)
                    .font(.title2)
                    .fontWeight(.semibold)
Step 12b — Show the recorded modifier in the breakdown

File: ContentView.swift · Where: the if modifier != 0 block near the end of the else block · Action: Replace it with

Dice Foundry code
                if rolledModifier != 0 {
                    Text("Dice \(subtotal), modifier \(formattedModifier(rolledModifier))")
                        .foregroundStyle(.secondary)
                }

What it does. The heading shows the stored notation string. The breakdown appears only if the roll had a modifier, and shows that modifier.

Why it is written this way. Now nothing in the result area reads selectedDie, quantity or modifier. Search the else block for those three names: they should not appear. The result area depends only on results, rolledModifier, rolledNotation, and the computed subtotal and total, which themselves depend only on those.

For reference, your complete result area should now match this:

Dice Foundry code
            if results.isEmpty {
                Text("Tap Roll Dice to begin")
                    .foregroundStyle(.secondary)
            } else {
                Text(rolledNotation)
                    .font(.title2)
                    .fontWeight(.semibold)

                ZStack {
                    Circle()
                        .fill(Color.orange.opacity(0.2))
                        .frame(width: 140, height: 140)
                    Text("\(total)")
                        .font(.system(size: 64, weight: .bold))
                }

                LazyVGrid(columns: resultColumns, spacing: 8) {
                    ForEach(results.indices, id: \.self) { index in
                        Text("\(results[index])")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(width: 44, height: 44)
                            .background(Color.orange.opacity(0.2))
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    }
                }

                if rolledModifier != 0 {
                    Text("Dice \(subtotal), modifier \(formattedModifier(rolledModifier))")
                        .foregroundStyle(.secondary)
                }
            }

What should happen. Build and run (⌘R). Continue with Step 13.

Step 13 — Test the finished behavior

Work through this short test script. It is the same kind of manual test you would run after changing a production system: a known input, an expected output, and a check that nothing else moved.

  1. Launch. The middle of the screen says "Tap Roll Dice to begin". There is no "0".
  2. Select D6, quantity 3, modifier +2. Roll. The heading says 3D6 + 2. Add the three chips in your head; the circle shows that sum plus 2. The breakdown says "Dice sum, modifier +2".
  3. Without rolling, tap the modifier plus button, the quantity plus button, and D20. The result area does not change at all. The stepper labels and die selection do change, because they describe the next roll.
  4. Roll again. Now the heading says 4D20 + 3, with four chips from 1 to 20.
  5. Select D20, quantity 2, modifier -4 (tap minus until the label reads "Modifier: -4"). Roll. The heading says 2D20 - 4, not 2D20 + -4. The total is the chip sum minus 4. The breakdown says "modifier -4".
  6. Set the modifier to 0 and roll. The heading has no modifier (for example 2D20), and the breakdown line disappears.
  7. Roll 1D4 with modifier -20 several times. The total can be negative (for example -18). That is mathematically correct for this notation, and the app shows it honestly.

If every step behaves as described, your Chapter 7 project matches the reference.

Expected Results

When you launch the app, the die buttons, the two steppers and the Roll Dice button are visible, and the middle of the screen shows a gray "Tap Roll Dice to begin" message. After rolling 3D6 with a +2 modifier, the screen looks approximately like this:

Illustrative mockup — not a screenshot

          [dice]  Dice Foundry

      [  D4  ]   [  D6  ]   [  D8  ]
      [ D10  ]   [ D12  ]   [ D20  ]

  Number of dice: 3                [ - | + ]
  Modifier: +2                     [ - | + ]

                  3D6 + 2

                 .-------.
                (   14    )
                 '-------'

              [4]  [2]  [6]

          Dice 12, modifier +2

              [ Roll Dice ]
Actual iOS Simulator screenshot — one D6 rolled with a +3 modifier

Figure: one D6 rolled with a +3 modifier: the heading reads "1D6 + 3", the die tile shows 3 and the total is 6. The number you roll will differ on your device.

Your numbers will differ, because the dice are random. What must hold every time:

  • The heading's quantity, die and modifier match the roll you made, even if you change the controls afterward.
  • The total equals the sum of the chips plus the modifier shown in the heading.
  • A negative modifier appears as - 4 in the heading and -4 in the stepper label and breakdown line.
  • The breakdown line exists only when the roll had a nonzero modifier.
  • No "0" result is shown before the first roll.

Reading This Like a Developer

Where execution begins for a roll

Nothing happens until the user taps Roll Dice. The tap runs the button's closure, { performRoll() }, which calls one function. Everything interesting starts there:

tap "Roll Dice"
  -> Button closure
     -> performRoll()
        -> isValidQuantity(quantity)          reads control state
           false -> print(...) and stop       (cannot happen with the Stepper)
           true  ->
              rollDice(count:sides:)          loop; rollDie() -> Int.random(in:)
              results = [...]                 state change 1
              rolledModifier = modifier       state change 2
              rolledNotation = notation(...)  state change 3
  -> SwiftUI notices @State changed, re-evaluates body
     -> if results.isEmpty   (now false) -> else block
        -> Text(rolledNotation)
        -> Text("\(total)") -> total -> subtotal -> sum(of: results) -> reduce
        -> ForEach over results -> one chip per die
        -> if rolledModifier != 0 -> breakdown line

Which variables hold state, and what they mean

Sort the state into two groups. Doing this for any screen you read is one of the fastest ways to understand it.

Group Properties Changed by Describes
Controls (input) selectedDie, quantity, modifier Die buttons, steppers The next roll
Last roll (output) results, rolledModifier, rolledNotation Only performRoll() The roll that happened
Derived (not stored) subtotal, total Nothing; computed on read Calculated from the last roll

A useful rule when reading or reviewing: output views should read output state. If you find a result view reading a control, ask whether that is intended. In Step 9 it was not.

Where a value originates and is modified

Follow the total of 14 in the worked example backward:

  • 14 is displayed by Text("\(total)").
  • total is computed: subtotal + rolledModifier = 12 + 2.
  • subtotal is computed: sum(of: results) = [4, 2, 6].reduce(0, +) = 12.
  • results was assigned once, in performRoll(), from rollDice, which got each value from Int.random(in: 1...6).
  • rolledModifier was assigned once, in performRoll(), from modifier, which the user set with the stepper.

There is exactly one place that writes each piece of last-roll state. That makes the code easy to reason about: if the result is wrong, the bug is in performRoll() or in the functions it calls.

Business logic versus presentation logic

  • Business logic is the rules of the domain: what counts as a valid quantity, how a total is calculated, what dice notation means. In this chapter: isValidQuantity, subtotal, total, the shape of notation.
  • Presentation logic decides how things look: formattedModifier (plus sign or not), whether the breakdown line appears, the placeholder text.

At the moment both live inside ContentView, mixed with layout. That is fine for an app this size. As the app grows, mixing them makes the view hard to read and the rules hard to test. You will move the rules out step by step: into a model in Chapter 8, a separate roller in Chapter 12, and a view model in Chapter 13.

How errors are handled

There is one failure path in this chapter: an invalid quantity. It is handled by refusing to roll and printing a line to the console. The user sees nothing change. That is acceptable here only because the Stepper makes the path unreachable in normal use. When you read code, look for failure paths that silently do nothing in places where the user would expect feedback; those deserve a closer look.

AI-Assisted Development: Reading AI-generated conditional code

When you ask an assistant to "add a modifier and show the notation", the first draft very often computes the notation and total in body from the live controls, exactly like Step 8. It looks right in a quick test and is wrong as soon as someone touches a control after rolling. Three things to check in generated code: (1) Does any result view read a control's state? (2) For negative numbers, does the output say + -4? (3) Does a formatter use String(format: "%+d", value)? That C-style format is compact and common in generated code, but it prints +0 for zero, which may not be what you want. When you direct an agent, state the rule explicitly: "The result must describe the roll that happened; changing controls after a roll must not change the displayed result." Clear acceptance criteria like that get you correct code much more reliably than "fix the bug".

Troubleshooting

"Switch must be exhaustive"

Switch must be exhaustive

Meaning. The compiler found possible values of the switch subject that no case handles. For formattedModifier, removing default: leaves negative numbers unhandled.

Likely causes. A missing default, or a default typed inside another case's block. Xcode often offers a fix-it to add missing cases; for an Int it will suggest a default.

How to investigate. Read each case and ask "which numbers does this match?" Then ask which numbers match none. Add default: as the last case.

"Missing return in instance method expected to return 'String'"

The message will be similar to:

Missing return in instance method expected to return 'String'

Meaning. At least one path through the function reaches its closing brace without returning a value.

Likely causes. In notation, forgetting the final else { return dice }, or writing else if modifier == 0 instead of else. Even though you know the three conditions cover every integer, the compiler does not analyze comparisons that way; it only sees that the last branch is conditional.

How to investigate. Trace each branch to its end and confirm each one says return. End an if chain that must return with a plain else.

"Use of '=' in a boolean context, did you mean '=='?"

The message will be similar to:

Use of '=' in a boolean context, did you mean '=='?

Meaning. You wrote assignment (=) where a comparison (==) belongs, such as if rolledModifier = 0.

How to investigate. Accept the fix-it, or change = to == (or to != if that is what you meant). Swift's refusal to treat assignment as a condition prevents a whole family of bugs found in older languages.

"Cannot find 'rolledModifier' in scope"

Cannot find 'rolledModifier' in scope

Meaning. The compiler does not know a property with that exact name in this context.

Likely causes. A typo (rolledModifer), a different capitalization, or doing Step 11 before Step 10. Also check that you added the properties inside struct ContentView and not after its closing brace.

How to investigate. Press ⇧⌘O, or simply search the file (⌘F) for rolledModifier and compare the spelling at the declaration and the use.

"Cannot convert value of type 'Int' to expected argument type 'Binding<...>'"

The message will be similar to:

Cannot convert value of type 'Int' to expected argument type 'Binding<Int>'

Meaning. The Stepper needs a two-way binding to change the value, and it received a plain Int.

Likely cause. value: modifier instead of value: $modifier. Note that the label uses modifier without $ (it only reads), and value: uses $modifier (it reads and writes). Both are correct in the same line.

The heading says "2D20 + -4"

Meaning. A logic error: the code compiles, but the negative branch is not producing the right text.

Likely causes. The else if modifier < 0 branch is missing, so negatives fall into a branch that uses +; or the negative branch uses \(modifier) instead of \(abs(modifier)), giving 2D20 - -4.

How to investigate. Put a temporary print(notation(quantity: 2, dieType: .d20, modifier: -4)) at the start of performRoll(), run, tap Roll Dice, and read the console. Remove the line when you are done.

The stepper label shows "+0"

Likely cause. The positive case is case 0...: instead of case 1...:, or the case 0: line is placed after the positive case. A switch runs the first matching case.

The result changes when you touch the controls after rolling

Meaning. Some part of the result area still reads control state.

How to investigate. Within the else block of if results.isEmpty, and in subtotal and total, search for modifier, quantity and selectedDie. The only acceptable matches are inside rolledModifier and inside formattedModifier(...) calls whose argument is rolledModifier.

The layout jumps when the breakdown line appears

Meaning. Not a bug. The Spacer() views above and below the result area share the leftover space, so adding or removing a line shifts things slightly. In Chapter 8 the layout changes to a scrolling page and this effect largely disappears.

Knowledge Check

  1. What is the value of !(3 > 2) || (5 == 5 && 1 > 4)? Explain how you evaluated it, including whether short-circuiting applied.
  2. formattedModifier uses case 1...: and default:. Why does Swift insist on the default:, and what would go wrong if the positive case were written case 0...:?
  3. The Stepper already limits quantity to 1...10. Give two concrete reasons the code still checks isValidQuantity(quantity) before rolling.
  4. Describe, in terms of state, why computing the heading from notation(quantity: quantity, dieType: selectedDie, modifier: modifier) inside body is a bug, and what change fixes it.
  5. For the roll "2D20 - 4" with dice 15 and 7, give the values of results, subtotal, rolledModifier, total and rolledNotation, with their Swift types.

Independent Challenge

Important: Commit before branching and switching

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.

Challenge: Challenge 1 — Rate the total

Below the result area's existing content, show a one-word rating of the roll's total: "Ouch" for totals of 0 or less, "Low" for 1 to 5, "Solid" for 6 to 14, and "High" for 15 or more. Write the rating as a function that takes an Int and returns a String, using a switch with range cases. The rating must appear only after a roll and must not change when the controls change.

Challenge: Challenge 2 — Natural 20 and natural 1

When the last roll was exactly one D20 and it showed 20, show "Natural 20!" in green; if it showed 1, show "Natural 1" in red. Show nothing in any other case, including two D20s or one D12 that shows 1. As with the notation, the message must describe the roll that happened: selecting a different die after rolling must not make the message appear or disappear.

Requirements, acceptance criteria and progressive hints are in the Chapter 7 Exercises document. Do the challenges on a separate Git branch, as described there.

Chapter Completion Checklist

  • I can write a Boolean expression with &&, || and !, and predict its value.
  • I can explain short-circuit evaluation and why it can prevent a crash.
  • I can write an if / else if / else chain and explain why order matters when conditions overlap.
  • I can write a switch on an Int using a single value, a closed range, a one-sided range and default.
  • I can explain why Swift requires a switch to be exhaustive.
  • ContentView has a modifier state property and a second Stepper bounded to -20...20.
  • formattedModifier shows +2, 0 and -4 correctly.
  • notation(...) produces 3D6 + 2, 2D20 - 4 and 1D8.
  • isValidQuantity guards the roll, and I can explain defense in depth.
  • The app shows "Tap Roll Dice to begin" before the first roll.
  • I can name the four numbers in a modified roll (individual results, subtotal, modifier, total) and point to each in my code.
  • Changing the controls after a roll does not change the displayed result, and I can explain why rolledModifier and rolledNotation exist.
  • I ran the test script in Step 13 and every step behaved as described.

Development Checkpoint

Save this chapter as a Git snapshot so you can always return to it.

In Xcode: choose Integrate → Commit… (in some Xcode versions the menu is Source Control → Commit…), check that ContentView.swift is included, type the message Chapter 7: modifiers, dice notation and conditional display, and commit. Then add the tag from Terminal, because tagging is quicker there.

In Terminal, from your project folder (the one that contains DiceFoundry.xcodeproj):

git add -A
git commit -m "Chapter 7: modifiers, dice notation and conditional display"
git tag chapter-07
git log --oneline -3

The last command should show your new commit at the top.

To compare your work with the reference, open Reference-Checkpoints/Checkpoint-07-Modifiers-and-Notation/DiceFoundry/ContentView.swift alongside your own ContentView.swift. For a precise line-by-line comparison in Terminal, use the path to your own project's file:

diff /path/to/Reference-Checkpoints/Checkpoint-07-Modifiers-and-Notation/DiceFoundry/ContentView.swift DiceFoundry/ContentView.swift

No output means the files are identical. Differences in the comment header at the top (author name, date) are harmless. Any other difference is worth a look: it is either a typo or a deliberate change you made, and you should know which.

Prediction Answers

Trace the formatter (Step 2). formattedModifier(-3) returns "-3" (not 0, not 1 or more, so default, and interpolation includes the minus sign). formattedModifier(0) returns "0". formattedModifier(7) returns "+7". formattedModifier(-20) returns "-20". If default: came first, the code would not compile: Swift requires default to be the last case in a switch. (Even in languages that allow it elsewhere, a catch-all placed first would match everything and make the later cases unreachable.)

Bounds (Step 4). isValidQuantity returns false for 0, true for 1, true for 10, and false for 11. The "simplified" version value >= 1 || value <= 10 returns true for all four. Any integer is either at least 1 or at most 10 (most are both), so an OR of those two comparisons is always true and the check validates nothing. The compiler does not warn about this; only reasoning or testing the boundaries catches it.

Notation (Step 5). "3D6 + 2", "2D20 - 4" (the negative branch uses abs(-4), which is 4), and "1D8" (zero modifier, so only the dice part).

Change the controls after a roll (Step 9). After the roll with dice 4, 2, 6, the screen shows 3D6 + 2, total 14, three chips, and "Dice 12, modifier +2". With the Step 8 code:

  • (a) After the modifier plus: 3D6 + 3, total 15, the same chips, "Dice 12, modifier +3". The total changed with no roll.
  • (b) After the quantity plus: 4D6 + 3, total 15, still three chips. The notation now claims four dice.
  • (c) After tapping D20: 4D20 + 3, total 15, the same three D6 values.

Every view that read quantity, selectedDie or modifier updated, because SwiftUI re-evaluates body whenever state it depends on changes. After Steps 10 to 12, none of the three taps changes the result area.