Dice Foundry Solutions and Answer Key

Chapter 4 Answers — State, Functions, and Random Numbers

Knowledge Check Answers

1. Parts of func rollDie(sides: Int) -> Int. The parameter is sides, its type is Int, and the return type (after ->) is Int. Because only one name is written, sides serves both as the argument label callers write (rollDie(sides: 6)) and as the name used inside the function. With func rollDie(withSides sides: Int) -> Int, the argument label becomes withSides, so callers must write rollDie(withSides: 6), while the code inside the function still uses sides. Nothing else about the function's behavior changes.

2. Plain var versus @State. A SwiftUI view is a structure, and inside body (and the closures written in it) the structure's own stored properties are read-only: self is immutable. Assigning to an ordinary property from the button's action therefore fails with "Cannot assign to property: 'self' is immutable." Even if it were allowed, it would not help: view values are recreated constantly, so the change would be lost, and SwiftUI would not know to update the screen. @State moves the value into storage that SwiftUI owns and keeps alive while the view is on screen. Writing to it is allowed, the value survives every recreation of the view, and each change makes SwiftUI recompute body.

3. What makes the number change. The tap runs the button's action closure. The closure calls rollDie(sides: 6), which returns a random number from Int.random(in: 1...6). The closure assigns that number to result. Because result is @State, SwiftUI marks the view as out of date, recomputes body after the closure finishes, and Text("\(result)") produces the new number. SwiftUI compares the new description with the old one and updates only the number on screen. No line of your code updates the screen; the only line responsible for the change is the assignment result = rollDie(sides: 6), and SwiftUI does the rest.

4. 1...6 versus 1..<6. 1...6 is a closed range: it includes both bounds, so it contains 1, 2, 3, 4, 5 and 6. 1..<6 is a half-open range: it includes the lower bound but not the upper bound, so it contains 1 through 5. A six-sided die needs 1...6; with 1..<6 a six could never be rolled.

5. Closures. A closure is a block of code that can be stored and passed around as a value, to be run later; it is like a function without a name. The button stores the closure written in braces after Button("Roll Dice") and runs it once each time the user taps the button. It does not run when the screen is described, which is why the app does not roll at launch.

Challenge Solutions

Challenge 1 — A twenty-sided dice roller

This solution makes three changes to ContentView.swift.

Change 1. File: ContentView.swift · Where: directly below @State private var result: Int = 0 · Action: Add

Example — not part of the Dice Foundry project
    @State private var dieSides: Int = 6

Change 2. File: ContentView.swift · Where: the caption line Text("Rolling a D6") · Action: Replace

Example — not part of the Dice Foundry project
            Text("Rolling a D\(dieSides)")

The .foregroundStyle(.secondary) line below it is unchanged.

Change 3. File: ContentView.swift · Where: the Button("Roll Dice") { ... } and its closing brace (keep the four modifier lines that follow it) · Action: Replace

Example — not part of the Dice Foundry project
            HStack(spacing: 16) {
                Button("Roll D6") {
                    dieSides = 6
                    result = rollDie(sides: dieSides)
                }
                Button("Roll D20") {
                    dieSides = 20
                    result = rollDie(sides: dieSides)
                }
            }
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)

The four modifier lines are the ones you already had; they now follow the HStack's closing brace instead of the single button's. rollDie(sides:) is unchanged.

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The verified project is in challenge-solutions/ch04-d20/.

Why it works:

  • rollDie(sides:) already accepts any number of sides, so rolling a D20 needs no new rolling logic, only a different argument. This is the payoff of making sides a parameter instead of hard-coding 6.
  • The caption has to reflect the last die rolled, which changes in response to taps, so it must come from state. dieSides is a second @State property, starting at 6 so the caption reads "Rolling a D6" before any roll.
  • Each button's action first records the die (dieSides = 6 or dieSides = 20), then rolls that die and stores the result. Both assignments happen inside one closure, and SwiftUI updates the screen once, after the closure finishes, so the number and the caption always change together and always match.
  • Passing dieSides (rather than repeating the literal 20) to rollDie guarantees that the die named in the caption is the die that was rolled. If the two ever disagreed, it would be because of a typo in one place.
  • .font, .buttonStyle, .controlSize and .tint all flow down to the views inside the container they are applied to, so applying them once to the HStack styles both buttons identically. This is the same "settings flow down" behavior you saw with .font and .foregroundStyle in Chapter 3.

Alternatives:

  • Change the existing button only. The simplest D20 roller replaces rollDie(sides: 6) with rollDie(sides: 20) and the caption with "Rolling a D20". It satisfies "a twenty-sided dice roller" but loses the D6, so it does not meet this challenge's requirements. It does show the key point: a parameterized function makes a new die a one-argument change. Not compile-tested as a separate project, but it differs from the reference only in a number and a string literal.
  • Repeat the modifiers on each button. Putting all four modifiers on each Button separately also works. It is longer and makes it easier for the two buttons to drift apart in style later.
  • Literal arguments. result = rollDie(sides: 20) with dieSides = 20 on the line above also works, but repeats the number, so the caption and the roll could drift apart if one is edited later.
  • Looking ahead. Two buttons for two dice is fine; six buttons for six dice is not. Chapter 5 introduces an enum listing every die type and a grid of buttons generated from it, with a single selectedDie state replacing dieSides. You have just built the small version of that idea.

Extra Practice Answers

Exercise 1 — Predict the output

D6 rolled 3
D20 rolled 17

Each call builds a local label from its own sides argument ("D6", then "D20"), interpolates it with the roll argument, and returns the finished string. The returned strings are stored in first and second, which are then printed in order.

Exercise 2 — Spot the bug

let result = rollDie(sides: 6) declares a new local constant named result inside the closure. It does not assign to the @State property result; it just happens to have the same name. The local constant disappears when the closure ends, the state property is never changed, and the screen never updates. It compiles because declaring a local constant with the same name as a property is legal in Swift (the local name hides the property inside the closure). The compiler does give you a clue: a warning similar to "Initialization of immutable value 'result' was never used." Fix: remove let so the line assigns to the property: result = rollDie(sides: 6). Lesson: let name = ... always creates something new; name = ... changes something that already exists.

Exercise 3 — Spot the bug

1..<sides is a half-open range: it excludes the upper bound. With sides equal to 6, the possible values are 1 through 5, so 6 can never appear. The fix is one character: replace ..< with ..., giving Int.random(in: 1...sides). This is a logic error, not a compile error, which is why the program runs without complaint. Chapter 12 writes an automated test that catches it.

Exercise 4 — Labels and names

Example — not part of the Dice Foundry project
    func rollDie(withSides sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }

The button's action becomes result = rollDie(withSides: 6). The first name in the parameter list (withSides) is the argument label used by callers; the second (sides) is the parameter name used inside the function. The function body does not change at all.

Exercise 5 — Predict the value

count ends at 14. The first call, addRolls(first: 2, second: 5), returns 7, so count becomes 7. The second call passes the current value of count for both arguments, addRolls(first: 7, second: 7), which returns 14, and that is stored back in count. The names first, second (parameters) and sum (a local constant) are local to the function; they exist only while each call runs. count is declared outside the function and is not visible inside it; its value reaches the function only because it is passed as an argument.