Dice Foundry Student Workbook

Chapter 4 — State, Functions, and Random Numbers

At the end of Chapter 3, Dice Foundry looks like a dice app but behaves like a poster: the die always shows 6, and the Roll Dice button only prints a message to the console. In this chapter the app comes alive. You write your first function, rollDie(sides:), which produces a random number between 1 and a given number of sides. You give the view its first piece of state, a value that can change while the app runs, and you connect the button to the function so that each tap stores a new roll in that state. Then you watch SwiftUI do the thing Chapter 3 promised: update the screen by itself whenever the state changes.

Along the way you learn three ideas that appear in almost every piece of Swift you will ever read: functions (with parameters, argument labels and return values), closures (code you hand to someone else to run later), and @State (how a SwiftUI view remembers a value). You also take apart the expression Int.random(in: 1...6) one character at a time, so that the next time you meet a random number or a range in AI-generated code, you know exactly what it means. By the end, pressing Roll Dice shows a random number from 1 to 6.

Learning Objectives

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

  • Explain what a function is and why code is organized into functions.
  • Declare a function with a parameter and a return type, and explain each part of the declaration.
  • Distinguish argument labels from parameter names, and call a function with the correct label.
  • Explain what return does and what happens when a function that promises a value does not return one.
  • Explain function scope: which names are visible inside a function and which are not.
  • Explain what a closure is, and identify the closure in a Button.
  • Explain why a plain var property cannot be changed inside a SwiftUI view, and what @State does differently.
  • Read @State private var result: Int = 0 token by token.
  • Describe the state-driven rendering loop: state changes, SwiftUI recomputes body, the screen updates.
  • Read Int.random(in: 1...6) token by token, including the closed range operator ..., and contrast it with the half-open range operator ..<.
  • Build a working six-sided dice roller and trace a single roll from the tap to the updated screen.

Concept Explanation

Functions: named, reusable pieces of work

A function is a named block of code that performs one task. You declare it once, giving it a name and the code to run. Later you call it by name whenever you need that task done.

You have already called many functions. print("Roll Dice tapped") calls Swift's print function. Spacer() and Text("6") look similar, because creating a value of a type uses the same call syntax. In this chapter you write a function of your own for the first time.

Functions exist for three reasons that matter to you directly:

  1. Naming. rollDie(sides: 6) says what it does. A reader does not need to decode the arithmetic inside it to understand the line that calls it.
  2. Reuse. Once a task is in a function, any number of places can call it. In Chapter 6 the same roll logic is used to roll several dice at once.
  3. Isolation. A function's inner details stay inside it. When a bug involves how a die is rolled, there is exactly one place to look.
Infrastructure Analogy: A function is a script with parameters

You have written shell functions or small scripts that take arguments and print or return a result: check_disk /var 90 runs the same logic against whatever path and threshold you pass in. A Swift function is the same idea, with stricter rules: the compiler knows the type of every argument and of the result, and refuses to build if a caller passes the wrong kind of value.

Here is the function you will add to Dice Foundry:

Dice Foundry code
    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }

Read it aloud as: "Declare a function named rollDie. It takes one input, called sides, which is an Int. It produces an Int. Inside, it creates a random number from 1 to sides, names it roll, and returns it to the caller."

Parameters: the inputs

A parameter is a named input to a function, declared inside the parentheses with a name and a type: sides: Int. Inside the function, sides behaves like a constant (let) holding whatever value the caller passed in. You cannot assign a new value to a parameter inside the function.

Parameters make a function general. A function that only rolls a six-sided die would be useful exactly once. A function that rolls a die with any number of sides is useful for the D4, D8, D10, D12 and D20 that Dice Foundry adds in Chapter 5, without writing a single new line of rolling logic.

For comparison, here is what a less general version would look like. It is not part of the project:

Example — not part of the Dice Foundry project
func rollSixSidedDie() -> Int {
    return Int.random(in: 1...6)
}

It works, but every new die type would need another nearly identical function. Moving the 6 out into a parameter is the first, smallest example of an idea you will see throughout the course: keep the logic in one place and pass in what varies.

Argument labels and parameter names

When you call rollDie, you write the parameter's name in front of the value:

Dice Foundry code
                result = rollDie(sides: 6)

The sides: in the call is called an argument label. The value after it, 6, is the argument: the actual value passed in for this call. Labels make calls read like sentences, and they are required: rollDie(6) does not compile. The compiler reports an error similar to "Missing argument label 'sides:' in call."

By default, a parameter's name is used for two jobs: as the label callers write, and as the name the code inside the function uses. Swift lets you separate those jobs by writing two names in the declaration: the first is the argument label (for callers), the second is the parameter name (for the function's own code). This example is not part of the project:

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

let value = rollDie(withSides: 20)

Callers write withSides:, and inside the function the value is called sides. Apple's own frameworks use this heavily to make calls read naturally. You have already seen one: in Int.random(in: 1...6), the label is in:, which reads well at the call site ("random in one through six"). Inside Swift's implementation, that parameter has a different, more descriptive name.

You may also see an underscore used as the argument label, as in func double(_ value: Int), which lets callers write double(4) with no label at all. The underscore is explained in Chapter 6. Dice Foundry's rollDie(sides:) uses the simple form, where one name serves as both label and parameter name.

Tip: How developers write a function's name

In documentation, error messages and conversation, a function is named together with its labels: rollDie(sides:). The labels are part of the function's identity. Two functions named rollDie with different labels are two different functions.

Return values and ->

The arrow -> in the declaration introduces the return type: the type of value the function hands back to its caller. -> Int means "this function produces an Int."

Inside the function, the return statement does two things at once: it ends the function immediately, and it hands its value back to the place where the function was called. Any code after a return in the same block never runs.

A function that declares a return type must return a value of that type on every path through it. If you write the function and forget the return roll line, the build fails with an error similar to:

Missing return in instance method expected to return 'Int'

You will also see a warning that roll was created but never used, which is the compiler's second clue that the value went nowhere.

Functions that do not produce a value simply leave out the arrow. print is an example: it does its job (writing to the console) and returns nothing useful.

Note: You might see a shorter version

If a function's body is a single expression, Swift lets you leave out the return keyword: func rollDie(sides: Int) -> Int { Int.random(in: 1...sides) }. AI-generated code often uses this short form. Dice Foundry uses a named constant and an explicit return because it makes each step visible and gives you a named value (roll) to inspect in the debugger in Chapter 12. Both forms compile to the same behavior.

Calling a function: the call becomes its value

When Swift reaches a function call, it pauses the current line, runs the function's body with the arguments you passed, and then replaces the call with the returned value. A useful way to read code is to perform that substitution in your head:

result = rollDie(sides: 6)

  1. Swift calls rollDie, with sides = 6
  2. Inside: roll = Int.random(in: 1...6)      suppose this gives 4
  3. Inside: return roll                       hands back 4
  4. The call is replaced by its value:  result = 4
Predict Before You Run: Trace a function call

Read this example (not part of the project) and predict the final value of total before checking Prediction Answers.

Example — not part of the Dice Foundry project
func bonus(for roll: Int) -> Int {
    let extra = roll * 2
    return extra + 1
}

var total = bonus(for: 4)
total += bonus(for: 1)

Function scope

In Chapter 2 you learned that a name declared inside braces is visible only inside those braces. Functions follow the same rule, and it has a name: function scope.

  • The parameter sides exists only while rollDie is running, and only inside its braces.
  • The constant roll is a local constant: it is created each time the function runs and disappears when the function returns.
  • Code outside the function, such as body, cannot see sides or roll. If you tried to print(roll) inside body, the build would fail with an error similar to "Cannot find 'roll' in scope."

The rule also works in the other direction. Code inside the function can see names from the surrounding structure. Because rollDie is declared inside ContentView, it could read ContentView's properties if it needed to. It deliberately does not: everything it needs arrives through its parameter, and everything it produces leaves through its return value. A function like that is easy to understand, easy to reuse, and (as you will see in Chapter 12) easy to test.

Infrastructure Analogy: Local variables are like a script's local variables

A local variable in a shell function vanishes when the function exits, and the caller only sees what the function echoes or returns. Swift's function scope is the same idea, enforced by the compiler instead of by convention.

Methods

A function declared inside a type is called a method. rollDie(sides:) lives inside struct ContentView, so it is a method of ContentView. That is why the compiler's messages say "instance method" rather than "function." For most purposes the two words are interchangeable; "method" just tells you where the function lives.

Where should the method go? Inside the structure's braces, but outside body. body describes the screen; rollDie performs a task. In Dice Foundry, methods go below the closing brace of body, which keeps the view description first and the supporting code after it.

Closures: code you hand over to run later

In Chapter 3 you wrote Button("Roll Dice") { print("Roll Dice tapped") } and learned that the braces after the button's title use trailing closure syntax. Now for what a closure actually is.

A closure is a block of code that you can store and pass around as a value, to be run later. It is like a function without a name. When SwiftUI builds the button, it does not run the code in the braces. It keeps the closure, and runs it each time the user taps the button.

Function Closure
Has a name Yes (rollDie) Usually not
Declared with func just { ... }
Typical use A task you call by name from several places A small piece of behavior handed to someone else (a button, a sort, an animation)
Can take parameters and return values Yes Yes (the button's closure takes none and returns nothing)

A closure can use names from the place where it was written. The button's closure is written inside ContentView's body, so it can use ContentView's result property and call ContentView's rollDie method. We say the closure captures what it needs from its surroundings. You do not have to do anything special to make this work.

In this chapter, the closure's contents change from printing a message to doing real work:

Dice Foundry code
            Button("Roll Dice") {
                result = rollDie(sides: 6)
            }

You will write closures yourself, store them in properties, and pass them between views in Chapter 10. Chapter 12 even stores a closure that generates random numbers, so tests can replace it with predictable values.

Reading This Like a Developer: Is this code running now, or later?

When you read SwiftUI code, ask of every block in braces: "Does this run when the screen is described, or later, in response to something?" The contents of VStack { } run every time body is computed. The contents of Button("Roll Dice") { } run only when the button is tapped. Mixing these up is behind many confusing bugs.

Why a plain var does not work in a view

Now the central question of the chapter. The die must show a different number after each tap, so we need a variable to hold the latest result. The obvious attempt is to add an ordinary property:

Broken code — for diagnosis practice
struct ContentView: View {
    var result: Int = 0

    var body: some View {
        Button("Roll Dice") {
            result = rollDie(sides: 6)
        }
    }
}

This does not build. On the assignment line, the compiler reports an error similar to:

Cannot assign to property: 'self' is immutable

What the message means. self is the current instance of the structure, the ContentView value whose code is running. "Immutable" means it cannot be changed. Inside body and the closures written in it, a structure's own stored properties are read-only. Swift structures are values, like the number 4, and code inside a structure cannot quietly rewrite the structure it belongs to unless that code is explicitly marked as allowed to. SwiftUI does not grant that permission to body.

Why SwiftUI is designed this way. Recall from Chapter 3 that views are lightweight descriptions that SwiftUI creates and throws away constantly. A ContentView value might be recreated every time its parent's body runs. Even if you could change result on one copy, the next copy would start again at 0, and SwiftUI would have no idea that anything changed, so it would never update the screen. A plain property is the wrong place to keep a value that must survive and must trigger updates.

What we need is storage that:

  1. lives outside the short-lived view value, so it survives every time the view is recreated;
  2. can be changed from the button's closure; and
  3. tells SwiftUI "something changed, read body again" whenever it is changed.

That is exactly what @State provides.

@State: storage that SwiftUI owns and watches

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

@State is a property wrapper: an annotation that wraps a property with extra behavior. For @State, the extra behavior is:

  • SwiftUI owns the storage. The first time ContentView appears on screen, SwiftUI creates a storage slot for result, puts the initial value 0 in it, and keeps it alive for as long as this view is on screen. Every new copy of the ContentView value is connected to that same slot.
  • Reading and writing go through the slot. When your code reads result, it reads the slot. When the button's closure assigns to result, it writes to the slot. Because the slot is not part of the immutable self, the assignment is allowed.
  • Writing schedules an update. When the value in the slot changes, SwiftUI marks the view as out of date and reads its body again shortly afterward.

You never call anything to make this happen. You only change the value.

Infrastructure Analogy: @State is a watched configuration value

Picture a configuration value stored in a key-value store that a controller watches. When someone changes the value, the controller notices and reconciles: it reads the desired-state manifest again with the new value and applies the differences. @State is that watched value; body is the manifest; SwiftUI is the controller. The view struct itself is like a manifest file rendered from a template: it can be thrown away and regenerated at any time, because the real value lives in the store.

@State is for values that this view owns and that only matter to the screen: the latest roll, which die is selected, whether a panel is expanded. It is not a database, and it does not survive quitting the app (Chapter 9 adds a file for that). When the app restarts, result starts at 0 again.

private: keeping state inside the view

private is an access control keyword. It means "only code inside this type can see this property." No other view can read or change ContentView's result directly.

Apple recommends marking @State properties private, and there is a good reason: state is owned by the view that declares it. If outside code could set it, it would be hard to know where a value came from. Keeping state private makes the answer to "who changes result?" easy: only code inside ContentView, which in this chapter means only the button's closure. In Chapter 10 you learn how a parent view deliberately shares a piece of state with a child view, using a binding, without giving up ownership.

State-driven rendering

Put the pieces together and you get the loop that drives every SwiftUI app:

  +-------------------------------------------------------------+
  |                                                             |
  v                                                             |
 body is computed                                               |
 Text("\(result)") reads result (currently 0)                   |
  |                                                             |
  v                                                             |
 SwiftUI draws the screen: the die shows 0                      |
  |                                                             |
  v                                                             |
 user taps Roll Dice                                            |
  |                                                             |
  v                                                             |
 button closure runs: result = rollDie(sides: 6)                |
  |                                                             |
  v                                                             |
 @State storage changes (0 -> 4)                                |
  |                                                             |
  v                                                             |
 SwiftUI marks ContentView as out of date  ---------------------+
 (then computes body again, compares old and new
  descriptions, and updates only the number on screen)

This is called state-driven rendering: the screen is always a function of the current state. You change state; the screen follows. You never write label.text = "4". In fact, there is no label object for you to write to; there is only your description, which says "the text is whatever result currently is."

Two details are worth knowing now:

  • Updates happen after your closure finishes. If a closure changes result twice, SwiftUI does not draw the intermediate value. It updates the screen once, with the final value, after the closure returns.
  • SwiftUI updates only what changed. When result changes from 0 to 4, the title, the circle, the caption and the button are identical in the new description, so SwiftUI leaves them alone and redraws only the number.
Predict Before You Run: Two assignments in one tap

Suppose the button's closure contained two lines: first result = rollDie(sides: 6), then result = result + 10. After one tap, what range of numbers could appear on screen? Would you ever see the first value briefly before the second? Check your answer in Prediction Answers.

Random number generation

Games need unpredictable numbers. Swift's integer type Int has a built-in way to produce them: Int.random(in:). You give it a range, and it returns one integer from that range, chosen at random, with every number in the range equally likely.

Where does the randomness come from? By default, Swift uses the system's random number generator, which the operating system seeds automatically from unpredictable sources. You do not need to "seed" it yourself, and you will not get the same sequence every time the app launches, which is a classic bug in older languages. For a dice app it is more than good enough.

Random behavior is, by nature, hard to check. If the die shows 4 twice in a row, is that a bug? (No: the chance is one in six.) Chapter 12 shows how to test code that uses randomness by temporarily replacing the random source with a predictable one. For now, you test by rolling many times and checking that every result is between 1 and 6 and that, over many rolls, every face appears.

Ranges: closed and half-open

A range describes a run of consecutive values between a lower and an upper bound. Swift has two operators for writing ranges, and the difference between them is one of the most common sources of off-by-one bugs:

Written Name Contains Example
1...6 closed range 1 up to and including 6 1, 2, 3, 4, 5, 6
1..<6 half-open range 1 up to but not including 6 1, 2, 3, 4, 5

A die with six sides needs the values 1 through 6 inclusive, so Dice Foundry uses the closed range 1...sides. The half-open form is the natural choice when counting positions in a list, which starts at 0; you will use it in Chapter 6.

The bounds can be any integer expressions, including names: 1...sides builds a range whose upper bound is whatever value sides holds at that moment. When sides is 6, it means 1...6; when it is 20, it means 1...20.

Predict Before You Run: One character different

What values can Int.random(in: 1..<6) produce? And what values can Int.random(in: 0...6) produce? Which of the three ranges (1...6, 1..<6, 0...6) is correct for a six-sided die? Answers in Prediction Answers.

Why the die shows 0 before the first roll

result starts at 0, because a @State property must have an initial value and 0 is the natural "nothing yet" integer. The die display shows whatever result holds, so before the first tap it shows 0, which is not a face on any real die. That is a small but real user-interface flaw, and it is deliberate for now. Fixing it properly needs a decision ("if nothing has been rolled yet, show a prompt instead of a number"), and decisions with if and else are the subject of Chapter 7. You will fix it there. Until then, the caption tells the user which die is being rolled, and the first tap replaces the 0.

AI-Assisted Development: Random numbers and state in AI-generated code

When you ask an AI assistant for a dice roller, you will see several ways of producing a random number. Int.random(in: 1...6) is the modern, correct form. You may also see (1...6).randomElement()!, which picks a random element from the range and force-unwraps the optional result; it works but adds an unnecessary optional and a crash-prone ! (Chapter 2 explained optionals; the ! means "crash if this is nil"). Older code from before Swift 4.2 uses Int(arc4random_uniform(6)) + 1, which works but is outdated and easy to get wrong. Watch the range in every version: 0...6, 1..<6 and 0..<6 all look plausible and are all wrong for a D6. For state, check that values that change on screen are @State (or another SwiftUI state mechanism you will learn later), and be suspicious of the opposite mistake: assistants sometimes mark every property @State, including values that never change, which works but hides which values the screen actually depends on. When directing an assistant, say what you want precisely: "Use @State private var result: Int, a separate rollDie(sides:) function that returns Int.random(in: 1...sides), and assign the result in the button's action."

Syntax Breakdown

@State private var result: Int = 0

This line is the first piece of state in Dice Foundry. Every token matters.

Token Meaning
@State A property wrapper from SwiftUI. The @ marks an attribute. @State tells SwiftUI to store this property's value in storage it owns, keep that value alive while the view is on screen, allow changes to it from inside the view, and recompute body when it changes.
private Access control. Only code inside ContentView can read or write this property. State belongs to the view that declares it.
var Declares a variable property, one whose value can change. @State requires var; a constant (let) could never change, so wrapping it in state would be meaningless.
result The property's name, in lowerCamelCase. It describes what the value means: the result of the latest roll.
: Introduces the type annotation.
Int The property's type: a whole number. Only integers can be stored here; trying to store a String is a compile error.
= Assigns the initial value.
0 The initial value, used the first time the view appears, before any roll.

How they work together: "Declare a variable named result, holding an Int that starts at 0, visible only inside ContentView, whose storage is owned and watched by SwiftUI so that changing it updates the screen." Remove @State and the property becomes ordinary, and assigning to it from the button fails with "Cannot assign to property: 'self' is immutable." Remove private and the code still compiles, but you lose the guarantee that only this view changes its state. Remove : Int and Swift infers Int from the 0, so the code still compiles; we write the type explicitly because, in a course and in code reviews, a visible type is easier to read.

func rollDie(sides: Int) -> Int {

Token Meaning
func Keyword: declares a function (here, a method, because it is inside ContentView).
rollDie The function's name: a verb phrase saying what it does.
( Opens the parameter list.
sides The parameter's name. Because only one name is written, it is also the argument label callers use: rollDie(sides: 6).
: Introduces the parameter's type.
Int The parameter's type. Callers must pass a whole number.
) Closes the parameter list.
-> "Returns." Introduces the return type.
Int The return type: the function produces a whole number.
{ Opens the function body.

let roll = Int.random(in: 1...sides)

Token Meaning
let Declares a constant. The roll is decided once and never changes inside this function.
roll The local constant's name. It exists only inside rollDie.
= Assigns the value on the right to the name on the left.
Int.random(in: 1...sides) The random number expression, explained token by token below. Its result is an Int, so Swift infers that roll is an Int.

Int.random(in: 1...6) — every part

This is the expression the assignment asks you to understand completely. In the project it is written with sides as the upper bound; here it is shown with the literal 6, which is what it means when sides is 6.

Token Meaning
Int The integer type. Here the type name is used on its own, not to declare a variable, because we are asking the type itself to do something.
. Member access: "the following thing that belongs to Int."
random The name of a function that belongs to the Int type rather than to any particular number. You call it on the type (Int.random) rather than on a value such as 4. Functions that belong to a type are called type methods; Chapter 9 explains the keyword static that creates them.
( Opens the argument list of the call.
in: The argument label. It reads as "random in ...". It is required; Int.random(1...6) does not compile.
1 The lower bound of the range: the smallest value that can be returned.
... The closed range operator. It builds a range that includes both bounds.
6 The upper bound: the largest value that can be returned. Because the range is closed, 6 is included.
) Closes the argument list.

How they work together: 1...6 builds a closed range containing 1, 2, 3, 4, 5 and 6. That range is passed, with the label in:, to the random function that belongs to Int. The function asks the system's random number generator for a value, picks one integer from the range with every value equally likely, and the whole expression evaluates to that integer. In rollDie, 1...sides builds the range from whatever sides holds, so the same line serves every die type.

Swift's other number types follow the same pattern. Double.random(in: 0...1), for example, produces a random decimal number between 0 and 1. Dice only need integers.

return roll

Token Meaning
return Ends the function and hands a value back to the caller.
roll The value handed back. Its type (Int) must match the declared return type (-> Int).

result = rollDie(sides: 6)

Token Meaning
result The @State property, being written to.
= Assignment: store the value on the right into the property on the left. (This is not a comparison; comparison is ==, which you meet in Chapter 5.)
rollDie Calls the method declared below body.
(sides: 6) Passes the argument 6 with the label sides:.

How they work together: Swift evaluates the right-hand side first: it calls rollDie(sides: 6), which returns a random number from 1 to 6. That number is then stored in result. Because result is @State, the store triggers SwiftUI to recompute body.

Text("\(result)")

You met string interpolation in Chapter 2. Here it has a new job. Text displays a string, but result is an Int. The string literal "\(result)" contains nothing but an interpolation, so it produces the number as text: if result is 4, the string is "4". Every time body is recomputed, this expression is evaluated again with the current value of result, which is how the new number reaches the screen.

Guided Implementation

In this section you turn the static interface into a working D6 roller in five steps, then run one deliberate experiment to see what goes wrong without @State.

Before you begin:

  • Open your Dice Foundry project from Chapter 3. If you did the Chapter 3 challenges on a branch, make sure you are back on the main line (git switch main).
  • Open ContentView.swift and show the canvas (⌥⌘↩).
  • If you want to be sure your starting point is correct, compare your file with Reference-Checkpoints/Checkpoint-03-Static-Interface/DiceFoundry/ContentView.swift.

The steps are ordered so the project builds after every step.

Step 1 — Add the state property

Step 1 — Add the result state

File: ContentView.swift · Where: inside struct ContentView: View {, as the first line, above var body: some View { · Action: Add

Dice Foundry code
struct ContentView: View {
    @State private var result: Int = 0

    var body: some View {

Type only the middle line and the blank line after it; the first and last lines are shown so you can see where it goes.

What it does: gives ContentView a piece of state named result, starting at 0, owned and watched by SwiftUI.

Why it is written this way: state properties go at the top of a view's structure, before body, so a reader sees at a glance what data the view depends on. The blank line separates "the data" from "the description of the screen". The property is private because only this view should change it, and its type is written explicitly so it is obvious what it holds.

What should happen: the project builds and the canvas looks exactly the same, still showing 6. Nothing reads result yet, so it has no visible effect.

Step 2 — Display the result

Step 2 — Show result in the die display

File: ContentView.swift · Where: inside the ZStack, the line Text("6") · Action: Replace

Before:

Example — not part of the Dice Foundry project
                Text("6")

After:

Dice Foundry code
                Text("\(result)")

Leave the .font(.system(size: 72, weight: .bold)) line below it unchanged.

What it does: the die display now shows the current value of result instead of a fixed "6".

Why it is written this way: Text needs a string, and result is an Int, so string interpolation converts it. Because body reads result here, SwiftUI now knows that this view depends on result and must be recomputed when it changes.

What should happen: the canvas shows 0 inside the circle. That is the initial value of result. It looks a little odd, and that is expected: see "Why the die shows 0 before the first roll." You fix it in Chapter 7.

Step 3 — Update the caption

Step 3 — Change the caption text

File: ContentView.swift · Where: the caption below the ZStack, the line Text("Tap Roll Dice to begin") · Action: Replace

Before:

Example — not part of the Dice Foundry project
            Text("Tap Roll Dice to begin")

After:

Dice Foundry code
            Text("Rolling a D6")

Leave the .foregroundStyle(.secondary) line below it unchanged.

What it does: the caption now tells the user which die the button rolls.

Why it is written this way: once the die shows a number, the instruction "Tap Roll Dice to begin" is no longer accurate after the first roll. "Rolling a D6" stays true at all times. "D6" is the standard tabletop notation for a six-sided die, and Chapter 5 makes this caption change when the user picks a different die.

What should happen: the canvas shows "Rolling a D6" under the circle.

Step 4 — Add the roll function

Step 4 — Add rollDie(sides:)

File: ContentView.swift · Where: inside struct ContentView, directly after the closing brace of body (the } that follows .padding()), and before the closing brace of the structure · Action: Add

Dice Foundry code
        .padding()
    }

    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }
}

Type only the blank line and the four lines of the function. The .padding() line, the } above the function, and the final } below it are already in your file; they are shown so you can see exactly where the function goes. After this step, the end of the structure has three closing braces in a row at decreasing indentation: none of them belongs to the function.

What it does: declares a method that takes a number of sides and returns a random number from 1 to that number, inclusive.

Why it is written this way:

  • The function is inside ContentView (so it is a method of the view, and the button's closure can call it) but outside body (because it is not part of the description of the screen).
  • sides is a parameter rather than a fixed 6, so the same function will roll any die from Chapter 5 onward.
  • The result is first stored in a named constant, then returned, so each step is visible and there is a named value to inspect while debugging in Chapter 12.
  • The function does not read or change result. It computes and returns; the caller decides what to do with the value. This separation (the rule for rolling a die versus where the result is displayed) is the first small example of separating business logic from presentation.

What should happen: the project builds and the canvas is unchanged. A function does nothing until it is called, and nothing calls it yet.

Warning: Watch the braces

The most common mistake in this step is pasting the function inside body (above .padding()), or after the structure's final brace (below the } that closes ContentView). Inside body, you get confusing errors because body expects views. After the structure's closing brace, the function is no longer part of ContentView. Use ⌃I to re-indent: func rollDie should start exactly four spaces from the left margin, the same as var body.

Step 5 — Roll when the button is tapped

Step 5 — Replace the button's action

File: ContentView.swift · Where: inside the Button("Roll Dice") { ... } closure, the line print("Roll Dice tapped") · Action: Replace

Before:

Example — not part of the Dice Foundry project
                print("Roll Dice tapped")

After:

Dice Foundry code
                result = rollDie(sides: 6)

The button and its modifiers now read:

Dice Foundry code
            Button("Roll Dice") {
                result = rollDie(sides: 6)
            }
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)

What it does: each tap calls rollDie(sides: 6) and stores the returned number in result.

Why it is written this way: the closure is the button's action, so this line runs once per tap, never while the screen is being described. The assignment to result is the only thing needed to update the screen: because result is @State, SwiftUI recomputes body, and Text("\(result)") shows the new value. There is no "refresh" call, and there does not need to be one.

What should happen: in the canvas (Live mode), tapping Roll Dice changes the number. Now run the real app with ⌘R and tap the button several times in the Simulator. Each tap should show a number from 1 to 6.

Tip: "The button did nothing!"

Sometimes a tap appears to do nothing. Before suspecting your code, remember that a random roll can produce the same number as the previous roll. The chance is one in six on every tap, so it happens often. Tap a few more times: if the number changes on most taps, everything is working. (Chapter 11 adds an animation on every roll, which makes repeated numbers visible.)

Step 6 — Experiment: remove @State (then restore it)

This step is an experiment to see the error from "Why a plain var does not work in a view" with your own eyes. It changes nothing permanently.

Step 6 — Temporarily remove @State

File: ContentView.swift · Where: the line @State private var result: Int = 0 at the top of struct ContentView · Action: Replace (then restore at the end of this step)

Broken code — for diagnosis practice
    private var result: Int = 0
  1. In the line @State private var result: Int = 0, delete @State (including the space after it), so the line reads private var result: Int = 0, as shown above.
  2. Build with ⌘B.
  3. Look at the line result = rollDie(sides: 6). Xcode marks it with an error similar to:
Cannot assign to property: 'self' is immutable
  1. Read the message with what you now know: inside the view, self (this ContentView value) is read-only, and result is now an ordinary stored property of self, so the button's closure cannot change it. With @State, the value lives in SwiftUI's storage instead, where it can change.
  2. Undo the edit (⌘Z) or type @State back in, so the line is again @State private var result: Int = 0.
  3. Build again with ⌘B. The error disappears.
Warning: Do not accept the Fix-it here

If Xcode offers a Fix-it for this error, do not apply it. Fix-its for this message are aimed at ordinary structures, not SwiftUI views. The right fix for a value that changes in a view is @State.

Step 7 — Optional: watch the values in the console

If you want to see each roll in the console as well as on screen, you can temporarily print it.

Step 7 — Temporarily print each roll

File: ContentView.swift · Where: inside the Button("Roll Dice") { ... } closure, directly after result = rollDie(sides: 6) · Action: Add (then Delete when you are done)

Example — not part of the Dice Foundry project
                print("Rolled \(result)")

What it does: after result has been assigned, the closure prints its new value, for example "Rolled 4". Because this line comes after the assignment, it prints the value that is about to appear on screen.

What should happen: run with ⌘R, tap a few times, and watch the console (⇧⌘Y). Each tap adds a line such as "Rolled 4", matching the number on screen. Then delete the print line so your file matches the reference checkpoint before you commit.

Your complete ContentView structure should now be:

Dice Foundry code
struct ContentView: View {
    @State private var result: Int = 0

    var body: some View {
        VStack(spacing: 24) {
            HStack {
                Image(systemName: "dice.fill")
                    .font(.title)
                    .foregroundStyle(.orange)
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
            }

            Spacer()

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

            Text("Rolling a D6")
                .foregroundStyle(.secondary)

            Spacer()

            Button("Roll Dice") {
                result = rollDie(sides: 6)
            }
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)
        }
        .padding()
    }

    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }
}

The import SwiftUI line and the #Preview block are unchanged.

Expected Results

When the app launches, before any tap:

Illustrative mockup — not a screenshot

+----------------------------------+
|   [dice]  Dice Foundry           |
|                                  |
|            .------.              |
|          /          \            |
|         |     0      |           |   <- initial value of result
|          \          /            |
|            '------'              |
|           Rolling a D6           |
|                                  |
|        [   Roll Dice    ]        |
+----------------------------------+

After tapping Roll Dice, the 0 is replaced by a number from 1 to 6, for example:

Illustrative mockup — not a screenshot

            .------.
          /          \
         |     4      |           <- a random value from 1 to 6
          \          /
            '------'
           Rolling a D6
Actual iOS Simulator screenshot — after one roll of a D6

Figure: the screen after one tap on Roll Dice, with the caption "Rolling a D6". The 5 is one random result; the numbers you roll will differ on your device.

Everything else on the screen stays the same. Each further tap shows a new random value (sometimes the same as before). The number changes instantly; there is no animation yet.

A quick manual test you can repeat in later chapters:

  1. Launch the app. The die shows 0 and the caption reads "Rolling a D6".
  2. Tap Roll Dice 30 times, noting each value.
  3. Every value is between 1 and 6. No 0, no 7.
  4. Over 30 taps, you are very likely to see every face from 1 to 6 at least once. If one face never appears in 30 rolls, roll 30 more before suspecting a bug; with true randomness, streaks happen.
  5. Stop the app (⌘.) and run it again (⌘R). The die shows 0 again, because @State lives in memory only. Persistence comes in Chapter 9.

Reading This Like a Developer

Now that the app has behavior, there is a real data flow to trace. Practice answering each question by pointing at specific lines.

Where does execution begin? As in Chapter 3: @main struct DiceFoundryApp → WindowGroup → ContentView() → ContentView.body. New in this chapter: when ContentView first appears, SwiftUI creates the storage for result and sets it to 0 before reading body.

Which variables hold state? Exactly one: @State private var result: Int. Everything else on screen is either a literal (the title, the caption, the colors) or derived from result (the number). When you open an unfamiliar view, list its @State properties first; they tell you what can change on this screen.

Which code runs when the button is pressed? Only the closure: result = rollDie(sides: 6). Here is the full trace of one roll:

1. User taps Roll Dice.
2. SwiftUI runs the button's action closure.
3. The closure evaluates the right-hand side: rollDie(sides: 6).
4. rollDie runs with sides = 6.
5.   Int.random(in: 1...6) asks the system random generator -> 4
6.   let roll = 4
7.   return roll  -> hands 4 back to the closure
8. The closure assigns: result = 4   (writes to SwiftUI's @State storage)
9. The closure finishes.
10. SwiftUI sees that result changed and marks ContentView out of date.
11. SwiftUI computes ContentView.body again.
12.   Text("\(result)") now produces Text("4").
13. SwiftUI compares the new description with the old one:
      only the number differs.
14. SwiftUI updates the number on screen. The die shows 4.

Where does a value originate, and where is it modified? The number originates in Int.random(in:) inside rollDie, travels out through return, and is stored in result by the button's closure. That closure is the only place that modifies result. The initial 0 originates in the property declaration. private guarantees that no code outside ContentView can modify it.

How does the interface respond to state changes? Automatically. body reads result; changing result causes SwiftUI to recompute body and apply the difference. There is no code anywhere that touches the screen directly.

Where is data saved? Only in memory, in SwiftUI's @State storage. Stopping the app discards it. Chapter 9 adds persistence.

How are errors handled? There are none to handle yet. Int.random(in:) cannot fail when given a valid range. (If sides were less than 1, the range 1...sides would be invalid, for example 1...0, and the app would crash at that line. rollDie is only ever called with 6 here. Chapter 12 discusses guarding against bad inputs.)

Business logic versus presentation logic. rollDie(sides:) is business logic: the rule "a die with N sides produces a number from 1 to N." It knows nothing about the screen. body is presentation logic: how to show the result. The button's closure is the glue that connects a user action to the business logic and stores the outcome as state. Keeping that separation, even in a tiny app, is what makes the larger refactors in Chapters 10, 12 and 13 straightforward.

Reading This Like a Developer: Follow the assignment

When you need to understand what a screen does, search the file for every place a @State property is assigned (result =). Each assignment is a place where the screen can change. In this chapter there is exactly one.

Troubleshooting

Cannot assign to property: 'self' is immutable

Cannot assign to property: 'self' is immutable

What it means: you are assigning to a stored property of the view from inside body or a closure in it, and that property is not state.

Likely causes: @State is missing from the property declaration (as in the Step 6 experiment), or you are assigning to a property you never meant to be state.

How to investigate: click the error to jump to the assignment, note the property name, then find its declaration at the top of the structure. If it should change while the app runs, it needs @State.

Missing argument label 'sides:' in call

Missing argument label 'sides:' in call

What it means: you called rollDie(6) without the label. Labels are part of the function's name and are required.

How to fix: write rollDie(sides: 6). Xcode's Fix-it for this error inserts the label correctly.

Incorrect argument label in call

Incorrect argument label in call (have 'side:', expected 'sides:')

What it means: the label you wrote does not match the declaration. Here, side: was written instead of sides:.

How to investigate: compare the call with the func rollDie(sides: Int) -> Int line. The message tells you what you wrote and what was expected. Code completion avoids this: type rollD and choose the suggestion.

Missing return in instance method expected to return 'Int'

Missing return in instance method expected to return 'Int'

What it means: the function promises (-> Int) to return an Int, but its body can end without a return.

Likely cause: the return roll line is missing or was accidentally deleted. You will usually also see a warning that roll was initialized but never used.

How to fix: add return roll as the last line of the function.

Cannot find 'roll' in scope

Cannot find 'roll' in scope

What it means: code outside rollDie tried to use the local constant roll. Local names exist only inside the function that declares them.

How to fix: use the function's return value instead. To get a roll in the button's closure, call rollDie(sides: 6) and store the result where you need it, as result = rollDie(sides: 6) does.

Cannot convert value of type 'Int' to specified type 'String'

Cannot convert value of type 'Int' to specified type 'String'

What it means: you tried to store an Int (for example the return value of rollDie) in something declared as a String.

How to fix: decide which type you really need. To display a number, keep it as an Int and convert it at the point of display with interpolation, as Text("\(result)") does.

The die always shows 0

Likely causes and checks:

  • The button's closure still contains print("Roll Dice tapped") instead of the assignment. Check Step 5.
  • The closure computes a roll but does not store it, for example let roll = rollDie(sides: 6) inside the closure. That creates a new local constant that disappears when the closure ends; result never changes. The line must assign to result.
  • The Text still shows a literal. Check that it reads Text("\(result)"), not Text("result") (which displays the word "result") or Text("0").
  • You are tapping in a paused or Selectable-mode preview. Run with ⌘R and tap in the Simulator.

The die sometimes shows 0, or never shows 6

These are logic errors: the code builds and runs but produces wrong results.

  • A 0 appears after rolling: the range starts at 0, as in Int.random(in: 0...sides). A die has no zero face.
  • 6 never appears: the range is half-open, as in Int.random(in: 1..<sides), which excludes the upper bound.

How to investigate: roll 30 or more times and write down the values; then read the range in rollDie character by character. Chapter 12 shows how to write an automated test that catches both of these bugs every time.

The function is in the wrong place

If you pasted rollDie inside body, you may see several confusing errors, often mentioning views or result builders, on lines that look fine. If you pasted it after the structure's final closing brace, calls to rollDie might still compile but the function is no longer part of ContentView, which will matter in later chapters.

How to investigate: select all and press ⌃I. func rollDie must be indented by exactly four spaces, like var body, and the file should end with the structure's } followed by the #Preview block. Compare with the complete listing at the end of Guided Implementation.

Knowledge Check

  1. In func rollDie(sides: Int) -> Int, what is the parameter, what is the parameter's type, and what is the return type? What would change if the declaration were func rollDie(withSides sides: Int) -> Int?
  2. Why does assigning to a plain var result = 0 from a button's action fail in a SwiftUI view, and what does @State change?
  3. Describe, step by step, what causes the number on screen to change after a tap. Which line of your code is responsible for updating the screen?
  4. What is the difference between 1...6 and 1..<6, and which one does a six-sided die need?
  5. The button's action is described as a closure. What is a closure, and when does the code inside this one run?

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.

Do this challenge on a separate Git branch (see the Exercises document for the commands). Progressive hints are in the Chapter 4 Exercises document, and a verified solution is in the Chapter 4 Answers document.

Challenge: Challenge 1 — A twenty-sided dice roller

Many tabletop games use a twenty-sided die, the D20. Extend Dice Foundry so the user can roll either a D6 or a D20. Replace the single Roll Dice button with two buttons side by side, "Roll D6" and "Roll D20", styled like the current button. Tapping "Roll D6" shows a random number from 1 to 6; tapping "Roll D20" shows a random number from 1 to 20. The caption shows which die was rolled last ("Rolling a D6" or "Rolling a D20"); before any roll it reads "Rolling a D6". Use what this chapter taught: @State, your existing rollDie(sides:) function (do not write a second rolling function), and string interpolation. Acceptance criteria: the project builds with no errors or warnings; 30 taps on Roll D20 produce only values from 1 to 20, including some above 6; the caption always matches the die that produced the number on screen; Roll D6 still produces only values from 1 to 6.

Chapter Completion Checklist

  • I can explain what a function is, and identify the name, parameter, parameter type and return type in rollDie(sides:).
  • I can explain the difference between an argument label and a parameter name.
  • I can explain what return does and what happens if it is missing.
  • I can explain why roll and sides are not visible outside rollDie.
  • I can explain what a closure is and when the button's closure runs.
  • I can explain the error "Cannot assign to property: 'self' is immutable" and why @State fixes it.
  • I can read @State private var result: Int = 0 token by token.
  • I can read Int.random(in: 1...6) token by token and explain ... versus ..<.
  • I can trace a roll from the tap to the updated screen.
  • I know why the die shows 0 before the first roll, and that Chapter 7 fixes it.
  • Tapping Roll Dice in the Simulator shows numbers from 1 to 6.
  • I restored @State after the Step 6 experiment and removed any temporary print from Step 7.
  • The project builds with no errors or warnings.

Development Checkpoint

Commit your work so you can return to this point.

In Xcode: Integrate → Commit... (the menu may be named Source Control in some versions), select all changed files, enter the message below, and commit. Or in Terminal, from your project folder:

git add -A
git commit -m "Chapter 4: Roll a D6 with @State and Int.random"
git tag chapter-04

To compare with the reference, open Reference-Checkpoints/Checkpoint-04-State-and-Random/DiceFoundry/ and compare ContentView.swift with yours. You can use FileMerge (Xcode → Open Developer Tool → FileMerge) or Terminal:

diff -u Reference-Checkpoints/Checkpoint-04-State-and-Random/DiceFoundry/ContentView.swift \
  /path/to/your/DiceFoundry/DiceFoundry/ContentView.swift

Differences in comments or the file header are fine. If you kept SwiftPractice.swift from Chapter 2, it appears only in your project; that is fine too. Make sure there is no leftover print line from the optional Step 7 and that @State is present.

This checkpoint is also one of the milestone listings in Appendix B of the workbook, so you can find the complete file there as well.

Prediction Answers

Trace a function call. total ends at 12. The first call, bonus(for: 4), computes extra = 4 * 2 = 8 and returns 8 + 1 = 9, so total starts at 9. The second call, bonus(for: 1), computes extra = 2 and returns 3. The compound assignment total += 3 makes total equal 12. Note the label: callers write for:, while the code inside the function uses the parameter name roll. And note that extra is local: each call gets its own extra, which disappears when the call returns.

Two assignments in one tap. The screen shows a number from 11 to 16. The first line stores a value from 1 to 6, and the second adds 10 to it. You would never see the first value on screen, even briefly: SwiftUI does not redraw in the middle of your closure. It waits until the closure finishes, then recomputes body once with the final value of result.

One character different. Int.random(in: 1..<6) produces 1, 2, 3, 4 or 5: the half-open range excludes 6, so a six can never be rolled. Int.random(in: 0...6) produces 0 through 6: seven possible values, including an impossible 0. Only 1...6 is correct for a six-sided die: six values, 1 through 6 inclusive. Both wrong versions compile and run without any error message, which is what makes range mistakes dangerous. Chapter 12 writes a test that catches them.