Dice Foundry Student Workbook

Chapter 6 — Arrays, Loops, and Multiple Dice

At the end of Chapter 5, the player can choose any of the six dice, but each tap of Roll Dice still produces a single number. Real games rarely work that way: "roll three D6" or "roll 2D20" is far more common than one die at a time. In this chapter you let the player choose how many dice to roll, from one to ten, and you show every individual die as well as their total. To do that, the app needs to hold a list of numbers instead of one number. That brings in the most-used collection type in Swift, the array, and the tools that go with it: adding and removing values, reading values by position, counting, looping with for, ranges, and adding everything up. You will write the sum the long way first, with a loop you can trace step by step, and only then replace it with the one-line reduce. You will also meet Stepper, SwiftUI's built-in control for choosing a quantity.

Learning Objectives

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

  • Explain what an array is and declare arrays with a type annotation, an array literal, or an empty literal.
  • Add values with append, remove values with remove(at:), removeLast() and removeAll(), and check count and isEmpty.
  • Read and change an array element by index, and explain why indexes start at 0.
  • Recognize the "Index out of range" runtime crash and explain what causes it.
  • Write for … in loops over an array and over a range, and use _ when you do not need the loop variable.
  • Explain the difference between the closed range 1...count and the half-open range 0..<count, and choose the right one.
  • Build an array in a loop by starting empty and appending.
  • Sum an array with a loop and an accumulator, then with reduce, and explain the difference between an imperative loop and a collection operation.
  • Use a computed property to derive a value (the total) from state.
  • Add a Stepper bound to state with $, limited to a range.
  • Display one view per array element with ForEach(results.indices, id: \.self), and explain why id: \.self is needed.
  • Lay out a variable number of items with an adaptive grid.

Concept Explanation

From one value to many

In Chapter 4, the result of a roll was a single Int:

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

Rolling three dice produces three numbers, and the app needs all of them: to show each die and to add them up. You could imagine three variables, firstDie, secondDie and thirdDie, as you did in the Chapter 2 playground. That falls apart quickly. The player can roll anywhere from one to ten dice, so you would need ten variables, and code to decide how many of them are in use. What you need is a single value that holds an ordered list of numbers of any length. That is an array.

Arrays

An array is an ordered collection of values of the same type. "Ordered" means each value has a position, and the order you put values in is the order you get them back. "Same type" means an array of Int holds only Ints.

The type of an array of integers is written [Int], read "array of Int". You can create one in several ways:

Example — not part of the Dice Foundry project
let rolls: [Int] = [4, 2, 6]     // array literal with a type annotation
let sameRolls = [4, 2, 6]        // type inferred as [Int]
var noRolls: [Int] = []          // empty array: the annotation is required
let alsoEmpty = [Int]()          // empty array using the type's initializer
let zeros = Array(repeating: 0, count: 3)   // [0, 0, 0]

The square brackets with comma-separated values are an array literal; you met one in Chapter 5 when you wrote the grid columns. An empty literal [] contains no values, so Swift cannot infer what type it should hold. You must say so, either with an annotation (: [Int]) or with the initializer form [Int](). Dice Foundry uses the annotation form, which reads most clearly.

let and var work exactly as in Chapter 2. A let array can never change: you cannot add, remove or replace its values. A var array can.

Counting and checking for empty

Two properties tell you about an array's size:

Expression Meaning For [4, 2, 6] For []
rolls.count How many values it holds 3 0
rolls.isEmpty Whether it holds no values false true

isEmpty means the same as count == 0, but it states the intention directly and is the idiomatic way to ask. You will use it a lot from Chapter 7 onward, when the app decides what to show before the first roll.

Indexes start at zero

Each value in an array has an index, its position, starting from 0:

rolls = [ 4,  2,  6 ]
index:    0   1   2        count = 3, last index = count - 1 = 2

You read a value with square brackets after the array's name, and you can replace a value in a var array the same way:

Example — not part of the Dice Foundry project
var rolls = [4, 2, 6]
let first = rolls[0]     // 4
let last = rolls[2]      // 6
rolls[1] = 5             // rolls is now [4, 5, 6]

Why 0 and not 1? An index is an offset from the start: the first value is zero steps from the start. Almost every mainstream programming language does the same. The practical consequence is the rule you must keep in your head: valid indexes run from 0 to count - 1.

Index out of range: a runtime crash

What happens if you ask for rolls[3] when the array has three values? There is no value at offset 3. Swift does not return garbage or nil; it stops the app immediately with a fatal error:

Fatal error: Index out of range

This is a runtime error. The compiler cannot know how many values an array will hold while the app runs, so rolls[3] compiles without complaint and only fails when that line actually executes. In Xcode, the app stops, the offending line is highlighted in red, and the message appears in the debug console. Chapter 12 covers runtime errors and the debugger in depth. For now, remember the cause: an index that is negative or greater than or equal to count.

Infrastructure Analogy: A bounds check that halts the process

Think of reading block 300 of a 256-block volume. A well-behaved storage layer refuses with an error instead of returning another volume's data. Swift goes one step further and terminates the process, on the principle that continuing with a wrong assumption is worse than stopping. It is a fail-fast design: the crash is loud, immediate, and points at the exact line.

Adding and removing values

Arrays declared with var can grow and shrink:

Code Effect on [4, 2, 6] Notes
rolls.append(3) [4, 2, 6, 3] Adds at the end.
rolls.remove(at: 1) [4, 6] Removes the value at index 1 and returns it (2). Crashes if the index is out of range.
rolls.removeLast() [4, 2] Removes the last value and returns it. Crashes if the array is empty.
rolls.removeAll() [] Removes everything. Safe on an empty array.

When an element is removed, the values after it move down one position, so their indexes change. After remove(at: 1), the 6 that was at index 2 is now at index 1.

remove(at:) and removeLast() give back the value they removed. You can store it (let removed = rolls.remove(at: 1)) or ignore it. Chapter 8 introduces insert(_:at:), which adds a value at a chosen position, and Chapter 9 uses removeLast() to keep the roll history from growing forever.

Repeating work: the for loop

A loop runs the same block of code several times. Swift's main loop is for … in, which runs its body once for each value in a sequence:

Example — not part of the Dice Foundry project
let rolls = [4, 2, 6]
for value in rolls {
    print(value)
}

This prints 4, then 2, then 6. On each pass (each iteration), the name after for, here value, is a new constant holding the current element. It exists only inside the loop's braces, the same scope rule you learned in Chapter 2.

A loop does not have to walk an array. It can walk a range of numbers:

Example — not part of the Dice Foundry project
for number in 1...3 {
    print("Roll number \(number)")
}

This prints "Roll number 1", "Roll number 2" and "Roll number 3".

Sometimes you want to repeat something a number of times but do not care which iteration you are on. Rolling three dice is exactly that: you need three rolls, but the roll itself does not depend on "this is roll 2". Swift lets you replace the loop variable's name with an underscore:

Example — not part of the Dice Foundry project
for _ in 1...3 {
    print("Rolling...")
}

The _ means "there is a value here, and I am deliberately not giving it a name". It tells the reader the loop is only counting, and it stops the compiler from warning that you declared a constant you never used. You will see _ in other places in Swift with the same meaning: "ignore this".

Closed and half-open ranges

You met the closed range 1...sides in Chapter 4: it includes both ends. Swift also has a half-open range, written with ..<, which includes the lower bound but stops before the upper bound:

Range Values Count
1...3 1, 2, 3 3
0..<3 0, 1, 2 3
1..<3 1, 2 2
0...3 0, 1, 2, 3 4

Both of the first two rows contain three values, so both work for "do this three times". Choose the one that matches what the numbers mean:

  • Counting things ("roll 1 to N dice", "the faces of a die") reads naturally as 1...count.
  • Walking indexes reads naturally as 0..<count, because valid indexes are 0 up to but not including count. Writing 0...count here is a classic off-by-one bug: the last iteration asks for rolls[count] and crashes with "Index out of range".

Arrays even give you their index range directly: rolls.indices is the half-open range 0..<rolls.count. You will use it later in this chapter.

One more rule: a closed range's lower bound must not be greater than its upper bound. 1...0 is not an empty range; it is a runtime crash. That matters for Dice Foundry, because the code that rolls dice uses 1...count. If count were ever 0, the app would crash. The Stepper you add in this chapter guarantees the quantity is always between 1 and 10, and Chapter 7 adds explicit validation.

Building an array with a loop

The core of this chapter's feature is a function that rolls a die several times and collects the results. The pattern, which you will see constantly in all kinds of code, has three parts:

  1. Start with an empty array (var rolls: [Int] = []).
  2. Loop, appending one value per iteration (rolls.append(...)).
  3. Return the filled array.

For a count of 3 and a D6, the array grows like this:

before loop:   []
iteration 1:   [4]
iteration 2:   [4, 2]
iteration 3:   [4, 2, 6]
return         [4, 2, 6]

Summing values: the loop way

To total the dice, you walk the array and keep a running sum in an accumulator, a variable that starts at a neutral value and is updated on every iteration:

Example — not part of the Dice Foundry project
var total = 0
for value in [4, 2, 6] {
    total += value
}
// total is 12

+= is the compound assignment operator from Chapter 2: total += value means total = total + value. Tracing it:

Iteration value total before total after
start 0
1 4 0 4
2 2 4 6
3 6 6 12

The starting value, 0, is chosen because adding 0 changes nothing, and an empty array should total 0.

This style is called imperative: you spell out how to get the answer, one instruction at a time. You control every step, which makes it easy to trace, debug, and extend (for example, to skip certain values).

Summing values: the collection-operation way

Summing is so common that arrays have a method that captures the whole pattern, reduce:

Example — not part of the Dice Foundry project
let total = [4, 2, 6].reduce(0, +)    // 12

reduce takes two things: a starting value and a way of combining "the result so far" with the next element. It does exactly what your loop did: start at 0, combine with 4 to get 4, combine with 2 to get 6, combine with 6 to get 12. The difference is who writes the loop. With reduce, the loop lives inside the method, and your code states what you want: "combine all of these with +, starting from 0".

This style is called a collection operation (or a functional or declarative style). Its advantages: shorter code, no mutable var, and a name that tells the reader the intent at a glance. Its costs: you must know what reduce does, and it is harder to put a breakpoint "inside" it or to add special cases.

Neither style is "right". Experienced Swift developers use reduce for simple sums and write explicit loops when the logic has several steps. You learn the loop first so that reduce is never magic: when you see it, you can mentally expand it back into the loop you wrote.

Infrastructure Analogy: Loop versus pipeline

The loop version is like a shell script that iterates over files and keeps a running total in a variable. The reduce version is like a one-liner that pipes values into a summing tool. Both produce the same number. The script is easier to step through and extend; the one-liner is easier to read once you know the tool.

Computed properties in a view

In Chapter 5 you added computed properties to DieType. A view can have them too. Dice Foundry's total is not stored anywhere; it is computed from the results whenever it is needed:

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

Why not store the total in its own @State variable and update it after each roll? Because then you would have two pieces of state that must agree, and any code path that changed results without updating total would show a wrong number. A computed property cannot disagree with the data it is computed from. This principle, derive what you can, store only what you must, keeps state small and bugs few. When results changes, SwiftUI re-evaluates body, body reads total, and total is recomputed from the new results.

Choosing a quantity: Stepper

SwiftUI's Stepper shows a label and a pair of minus and plus buttons. Each tap moves a number down or up by one, and you can limit the number to a range. It is the standard iOS control for small, whole-number quantities, which is exactly what "number of dice" is.

Example — not part of the Dice Foundry project
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)

The Stepper needs to change quantity, not just read it. That is what the $ in $quantity is for. Writing $ before the name of a @State property gives a two-way connection to that state, which SwiftUI calls a binding: the Stepper can read the current value to decide whether its buttons are enabled, and write a new value when tapped. For now, read $quantity as "a two-way connection to quantity"; Chapter 10 explains bindings fully. When the Stepper writes a new value, quantity changes, and because it is @State, body runs again and the label shows the new number.

The in: 1...10 range is enforced by the Stepper: at 1 its minus button is disabled, at 10 its plus button is disabled. That is how the app guarantees the quantity is never 0, which, as you saw, would crash the 1...count loop.

Showing a variable number of results

The result chips need a layout that handles anything from one to ten items. In Chapter 5 you used three fixed flexible columns. This time you use an adaptive column:

Example — not part of the Dice Foundry project
let resultColumns = [
    GridItem(.adaptive(minimum: 44))
]

A single adaptive GridItem means "fit as many columns as you can, each at least 44 points wide". On an iPhone, that is around six or seven chips per row; ten dice wrap onto a second row automatically.

To make one chip per result, you use ForEach again. In Chapter 5, ForEach(DieType.allCases) worked because DieType is Identifiable. Int is not Identifiable, and the values in results are not unique anyway: three dice can easily show [4, 4, 2]. So instead of walking the values, you walk their indexes, which are always unique:

Example — not part of the Dice Foundry project
ForEach(results.indices, id: \.self) { index in
    Text("\(results[index])")
}
  • results.indices is the range 0..<results.count, for example 0..<3.
  • id: \.self tells ForEach "use each element itself as its identity". The elements here are the index numbers 0, 1, 2, which are unique, so each is a perfect ID. \.self is a key path, a way of naming a property without reading it; \.self means "the whole value". You will see key paths again occasionally; you do not need more than this for now.
  • Inside the closure, index is the current index, and results[index] reads the value at that position.

Using indexes as identities is fine here because the whole results array is replaced on every roll. Chapter 8 introduces a better tool for longer-lived lists: a struct with its own unique id, so ForEach can use it directly.

AI-Assisted Development: Loops, reduce, and indexes in generated code

AI assistants often jump straight to dense collection code such as results.reduce(0, +) or chains of operations on one line. When you meet a reduce you do not understand, ask the assistant to "rewrite this as an explicit for loop with an accumulator", then compare the two. Also watch for two common bugs in generated code: for i in 0...array.count (one iteration too many, "Index out of range"), and ForEach(values, id: \.self) on an array that can contain duplicates, which gives two views the same identity and can cause rows to display incorrectly or log warnings. Indexes or a proper Identifiable type avoid that.

Syntax Breakdown

An array state property

Example — not part of the Dice Foundry project
@State private var results: [Int] = []
Token Meaning
@State private var As in Chapter 4: view-owned state, private to this view, changeable.
results The name. Plural, because it holds many values.
: A type annotation follows.
[Int] The type: an array whose elements are Int.
= Initial value follows.
[] An empty array literal. The annotation tells Swift its element type.

Appending

Example — not part of the Dice Foundry project
rolls.append(rollDie(sides: sides))
Token Meaning
rolls A var array.
.append( Method that adds one value to the end. It changes the array, so the array must be var.
rollDie(sides: sides) The value to add: the result of calling your Chapter 4 function.
) Ends the call.

Indexing

Example — not part of the Dice Foundry project
results[index]
Token Meaning
results The array.
[ ] Subscript: access by position.
index An Int from 0 to count - 1. Anything else crashes at run time.

A for loop that ignores its counter

Example — not part of the Dice Foundry project
for _ in 1...count {
    rolls.append(rollDie(sides: sides))
}
Token Meaning
for Begins a loop.
_ "I do not need the current value."
in Separates the loop variable from the sequence.
1...count Closed range: 1, 2, …, count. The loop runs count times.
{ ... } The body, executed once per value in the range.

Half-open range

Example — not part of the Dice Foundry project
0..<count
Token Meaning
0 Lower bound, included.
..< Half-open range operator: up to but not including the upper bound.
count Upper bound, excluded.

reduce, token by token

Example — not part of the Dice Foundry project
values.reduce(0, +)
Token Meaning
values The array being reduced, [Int].
.reduce A method on collections that combines all elements into one value.
( Begins the arguments.
0 The initial result: what you get for an empty array, and the starting point otherwise. Its type (Int) is the type of the final result.
, Separates the arguments.
+ The combining step. In Swift, an operator is also a function: + takes two Ints and returns their sum. Passing it here is the same as passing the closure { partial, value in partial + value }. reduce calls it once per element with the result so far and the next element.
) Ends the call. The whole expression evaluates to the final result.

For [4, 2, 6], reduce computes ((0 + 4) + 2) + 6 = 12.

Stepper

Example — not part of the Dice Foundry project
Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
Token Meaning
Stepper A SwiftUI control with minus and plus buttons.
"Number of dice: \(quantity)" The label, using string interpolation to show the current value.
value: Argument label: the number the Stepper controls.
$quantity A two-way connection (binding) to the quantity state. Chapter 10 explains bindings fully.
in: 1...10 The allowed range. The Stepper will not go below 1 or above 10.

ForEach over indexes

Example — not part of the Dice Foundry project
ForEach(results.indices, id: \.self) { index in
Token Meaning
ForEach( Build one view per element.
results.indices The range of valid indexes, 0..<results.count.
id: Argument label: how to identify each element.
\.self Key path meaning "the element itself". Each index number is its own ID.
{ index in Trailing closure; index is the current index.

Guided Implementation

You will practise arrays and loops in a playground first, then add the quantity control, the rolling and summing functions, the array state, and finally the display of individual results. The project builds after every step.

Start from your completed Chapter 5 project. If you want to be sure your starting point matches, compare it with Reference-Checkpoints/Checkpoint-05-Dice-Selection.

Step 1 — Practise creating and reading arrays

Playground practice is not part of the app; the reference checkpoint does not include it. If you deleted SwiftPractice.swift, recreate it as in Chapter 5, Step 6: File → New → File from Template... → Swift File, named SwiftPractice, with the DiceFoundry target checked, and change its import to import Playgrounds.

Step 1 — Add an Arrays playground

File: SwiftPractice.swift · Where: at the end of the file · Action: Add

Example — not part of the Dice Foundry project
#Playground("Arrays") {
    var rolls: [Int] = []
    print(rolls.isEmpty, rolls.count)

    rolls.append(4)
    rolls.append(2)
    rolls.append(6)
    print(rolls)
    print(rolls.count)
    print(rolls[0], rolls[2])

    rolls[1] = 5
    print(rolls)

    let noRolls = [Int]()
    let threeZeros = Array(repeating: 0, count: 3)
    print(noRolls, threeZeros)
}
Predict Before You Run: Arrays playground

Before you open the canvas, write down what each of the six print lines shows. Answers are in Prediction Answers.

What next: open the canvas (⌥⌘↩) and select the "Arrays" playground. Compare its output with your predictions. Notice that print shows an array in square brackets with commas, just like the literal.

Step 2 — Practise removing values

Step 2 — Add a Removing values playground

File: SwiftPractice.swift · Where: at the end of the file · Action: Add

Example — not part of the Dice Foundry project
#Playground("Removing values") {
    var rolls = [4, 2, 6, 3, 1]

    let removed = rolls.remove(at: 1)
    print(removed, rolls)

    rolls.removeLast()
    print(rolls)

    rolls.removeAll()
    print(rolls, rolls.isEmpty)
}
Predict Before You Run: Removing values

What are removed and rolls after remove(at: 1)? What is rolls after removeLast()? Answers are in Prediction Answers.

What next: check the canvas. Then try two experiments, one at a time, and undo each afterward: change remove(at: 1) to remove(at: 5), and add a second rolls.removeLast() after removeAll(). Each compiles, and each stops the playground with a runtime error, because there is no index 5 in a five-element array and there is no last element in an empty one.

Step 3 — Practise loops and ranges

Step 3 — Add a Loops and ranges playground

File: SwiftPractice.swift · Where: at the end of the file · Action: Add

Example — not part of the Dice Foundry project
#Playground("Loops and ranges") {
    let rolls = [4, 2, 6]

    for value in rolls {
        print(value)
    }

    for index in 0..<rolls.count {
        print("Index \(index) holds \(rolls[index])")
    }

    for number in 1...3 {
        print("Roll number \(number)")
    }

    for _ in 1...3 {
        print("Rolling...")
    }
}

What it does: shows the three loop forms you need: over values, over indexes with a half-open range, and over a closed range, with and without a loop variable.

What next: check the canvas output. Then change 0..<rolls.count to 0...rolls.count and look again. The playground stops with "Index out of range" on the fourth iteration, because index 3 does not exist. Change it back.

Step 4 — Practise summing

Step 4 — Add a Summing playground

File: SwiftPractice.swift · Where: at the end of the file · Action: Add

Example — not part of the Dice Foundry project
#Playground("Summing") {
    let rolls = [4, 2, 6]

    var total = 0
    for value in rolls {
        total += value
    }
    print(total)

    print(rolls.reduce(0, +))
    print(rolls.indices)
}

What it does: computes the same sum both ways, and shows what indices looks like.

What next: both sums print 12. print(rolls.indices) prints 0..<3: the half-open range of valid indexes. You now have every tool the app needs.

Step 5 — Add the quantity state

Switch to ContentView.swift.

Step 5 — Add quantity

File: ContentView.swift · Where: inside struct ContentView, directly after @State private var selectedDie: DieType = .d6 · Action: Add

Dice Foundry code
    @State private var quantity: Int = 1

What it does: stores how many dice to roll. It starts at 1, so the app behaves as before until the player changes it.

What next: build with ⌘B.

Step 6 — Add the Stepper

Step 6 — Add a Stepper below the die grid

File: ContentView.swift · Where: in body, after the closing brace of the LazyVGrid and one blank line, before the first Spacer() · Action: Add

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

What it does: shows "Number of dice: 1" with minus and plus buttons on the right. Tapping them changes quantity within 1 to 10.

Why it is written this way: a Stepper is the native iOS control for a small whole number, so players already know how it works. The label includes the value so the player always sees the current count. $quantity gives the Stepper a two-way connection to the state; Chapter 10 explains bindings fully. The range is part of the control, so invalid quantities are impossible by construction.

What next: look at the preview, or run the app (⌘R). Tap plus a few times: the label counts up. At 10, the plus button dims; at 1, the minus button dims. Rolling still rolls only one die, because nothing uses quantity yet.

Step 7 — Add rollDice(count:sides:)

Step 7 — Add a function that rolls several dice

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of rollDie(sides:), with one blank line between them · Action: Add

Dice Foundry code
    func rollDice(count: Int, sides: Int) -> [Int] {
        var rolls: [Int] = []
        for _ in 1...count {
            rolls.append(rollDie(sides: sides))
        }
        return rolls
    }

What it does: rolls a die with sides faces count times and returns all the results as an array.

Why it is written this way:

  • The return type -> [Int] says "this function gives back an array of integers".
  • var rolls: [Int] = [] starts empty. It must be var because append changes it, and it needs the annotation because [] alone has no element type.
  • for _ in 1...count repeats count times. The counter is unused, so it is _. The closed range reads naturally as "roll 1 through count".
  • It reuses rollDie(sides:) instead of calling Int.random again, so there is still exactly one place that defines what a single roll means.
  • rolls is a local variable: it exists only while the function runs. The function returns a copy of the finished array to the caller.

What next: build with ⌘B. Nothing calls this function yet.

Step 8 — Add sum(of:) as a loop

You will replace the body of this function with a shorter version in Step 13. Type the loop version first anyway: running it and seeing it work is what makes the shorter version understandable.

Step 8 — Add a loop-based sum function (temporary body)

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of rollDice(count:sides:), with one blank line between them · Action: Add

Example — not part of the Dice Foundry project
    func sum(of values: [Int]) -> Int {
        var total = 0
        for value in values {
            total += value
        }
        return total
    }

What it does: adds up every value in the array it is given, using an accumulator.

Why it is written this way: the argument label of and parameter name values (Chapter 4) make the call read like English, sum(of: results), while the body uses the clearer name values. The accumulator starts at 0 so an empty array sums to 0. return total hands the result back; because the body is more than one expression, return is required.

Note: Two things named total

In the next step you add a computed property named total to ContentView. The var total = 0 here is a different variable: a local variable that exists only inside sum(of:). Inside the function, the name total refers to the local variable, which hides (or shadows) the property of the same name. This is the scope rule from Chapter 2 at work. It is harmless here, and it disappears in Step 13 when the loop is replaced.

What next: build with ⌘B.

Step 9 — Add the results array and the total

Step 9 — Add results state and a computed total

File: ContentView.swift · Where: two places, described below · Action: Add

First, directly after @State private var quantity: Int = 1:

Dice Foundry code
    @State private var results: [Int] = []

Then, after the closing ] of the columns property and one blank line, before var body:

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

What it does: results will hold every die from the latest roll; it starts empty because nothing has been rolled. total derives the sum from results whenever it is read.

Why it is written this way: only the individual values are state; the total is derived, so it can never disagree with them. The old result property still exists for the moment, so the project keeps building while you switch over.

What next: build with ⌘B.

Step 10 — Make the Roll Dice button roll several dice

Step 10 — Change the roll button's action

File: ContentView.swift · Where: inside the Button("Roll Dice") action closure · Action: Replace

Before:

Example — not part of the Dice Foundry project
                result = rollDie(sides: selectedDie.sides)

After:

Dice Foundry code
                results = rollDice(count: quantity, sides: selectedDie.sides)

What it does: rolls quantity dice of the selected type and stores the whole array in results, replacing the previous roll.

Why it is written this way: the button reads two pieces of state, quantity and selectedDie, and writes one, results. A single assignment means the screen updates once with the complete roll.

What next: build with ⌘B. The circle still shows result, which is no longer updated, so do not run yet.

Step 11 — Show the total in the circle

Step 11 — Display total instead of result

File: ContentView.swift · Where: inside the ZStack, the Text after Circle() · Action: Replace

Before:

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

After:

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

Keep the .font(...) line below it unchanged for now.

What it does: the big number now shows the sum of all dice in the latest roll.

What next: build with ⌘B.

Step 12 — Remove the old result state

Step 12 — Delete result

File: ContentView.swift · Where: the first line inside struct ContentView · Action: Delete

Delete this line:

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

Why: nothing reads or writes result any more. Leaving unused state around confuses readers ("what updates this?"). The build tells you if anything still uses it: if you see "Cannot find 'result' in scope", a step above was missed.

The top of your struct should now be:

Dice Foundry code
struct ContentView: View {
    @State private var selectedDie: DieType = .d6
    @State private var quantity: Int = 1
    @State private var results: [Int] = []

What next: run the app (⌘R). Before rolling, the circle shows 0: results is empty and the sum of an empty array is 0. Set the Stepper to 3, keep D6, and tap Roll Dice several times. The total should always be between 3 and 18. Set it to 10 and select D20: totals between 10 and 200. Your loop-based sum is doing the work.

Predict Before You Run: Trace the loop sum

Suppose rollDice returns [5, 1, 3, 6]. Write down the value of the local total after each iteration of the loop in sum(of:), and what the circle shows. Answers are in Prediction Answers.

Step 13 — Replace the loop with reduce

Step 13 — Replace the body of sum(of:)

File: ContentView.swift · Where: the body of func sum(of values: [Int]) -> Int · Action: Replace

Replace the four lines between the function's braces (var total = 0 through return total) so the whole function reads:

Dice Foundry code
    func sum(of values: [Int]) -> Int {
        values.reduce(0, +)
    }

What it does: exactly what the loop did. reduce starts with 0 and combines it with each value using +.

Why it is written this way: the loop was correct, and you have seen it work, but summing is a standard operation and reduce(0, +) says it in one line with no mutable variable. Because the body is now a single expression, return is not needed. The function's name, parameters and return type are unchanged, so nothing that calls it needs to change. That is a small example of a refactoring: changing how code works internally without changing what it does.

What next: run the app again (⌘R) and repeat the tests from Step 12. The behavior should be identical. If you want to be sure, keep the Stepper at 1 and compare: the total is always the single die's value.

Step 14 — Update the caption

Step 14 — Include the quantity in the caption

File: ContentView.swift · Where: in body, the caption Text below the ZStack · Action: Replace

Before:

Example — not part of the Dice Foundry project
            Text("Rolling a \(selectedDie.name)")

After:

Dice Foundry code
            Text("Rolling \(quantity)\(selectedDie.name)")

Keep .foregroundStyle(.secondary) below it.

What it does: the caption now uses standard dice notation: "Rolling 3D6", "Rolling 1D20". There is deliberately no space between the two interpolations, because dice notation writes the count directly before the "D".

What next: look at the preview. It reads "Rolling 1D6". Change the Stepper and the die in the running app; the caption follows both immediately, even before you roll.

Step 15 — Define the result grid's columns

Step 15 — Add resultColumns

File: ContentView.swift · Where: inside struct ContentView, after the closing ] of columns and one blank line, before var total · Action: Add

Dice Foundry code
    let resultColumns = [
        GridItem(.adaptive(minimum: 44))
    ]

What it does: describes a grid that fits as many columns as possible, each at least 44 points wide.

Why it is written this way: the number of results varies from 1 to 10, so a fixed number of columns would either waste space or overflow. One adaptive item lets the grid decide. 44 points is Apple's recommended minimum size for a tappable target, and it makes a comfortable square chip for a one- or two-digit number.

What next: build with ⌘B.

Step 16 — Show each individual die

Step 16 — Add the result chips

File: ContentView.swift · Where: in body, after the caption's .foregroundStyle(.secondary) line and one blank line, before the second Spacer() · Action: Add

Dice Foundry code
            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))
                }
            }

What it does: for every index in results, shows that die's value in a small square chip.

Why it is written this way:

  • results.indices provides unique identities even when two dice show the same number, and id: \.self tells ForEach to use each index as its own ID.
  • results[index] is always safe here, because indices only contains valid indexes.
  • .frame(width: 44, height: 44) makes every chip the same size whether it shows 3 or 17.
  • .background(Color.orange.opacity(0.2)) fills the area behind the text with the same pale orange as the big circle, so the chips visually belong to the result.
  • .clipShape(RoundedRectangle(cornerRadius: 8)) trims that square background to a rounded square. RoundedRectangle is a shape like Circle; Chapter 11 uses shapes and rounded corners much more.
  • When results is empty, ForEach produces nothing and the grid takes no space, so the screen before the first roll looks as it did.

What next: run the app (⌘R). Choose 5 and D6, then roll. You should see the total in the circle, "Rolling 5D6" beneath it, and five chips whose values add up to the total. Check the arithmetic yourself a few times.

Step 17 — Make room for the new controls

The screen now has more content: a Stepper and up to two rows of chips. Three small adjustments keep everything comfortably on screen.

Step 17 — Tighten spacing and shrink the circle

File: ContentView.swift · Where: two places in body, described below · Action: Replace

First, the opening of the main stack. Before:

Example — not part of the Dice Foundry project
        VStack(spacing: 24) {

After:

Dice Foundry code
        VStack(spacing: 20) {

Then the ZStack with the circle. Before:

Example — not part of the Dice Foundry project
            ZStack {
                Circle()
                    .fill(Color.orange.opacity(0.2))
                    .frame(width: 160, height: 160)
                Text("\(total)")
                    .font(.system(size: 72, weight: .bold))
            }

After:

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

What it does: reduces the space between sections from 24 to 20 points, the circle from 160 to 140 points, and the total's font from 72 to 64 points.

Why: with ten D20s the total can reach 200, three digits wide, and the screen must also fit the Stepper and two rows of chips on smaller iPhones. Smaller values keep the layout balanced without scrolling. (Chapter 8 makes the screen scrollable when the history list arrives.)

What next: run the app and go to Step 18.

Step 18 — Test the whole feature

Run the app (⌘R) and work through this manual test:

  1. At launch: D6 selected, "Number of dice: 1", circle shows 0, caption "Rolling 1D6", no chips.
  2. Roll once: one chip, and the circle shows the same number.
  3. Set the quantity to 3 and roll: three chips; the circle shows their sum. Check it in your head.
  4. Tap minus until it stops: it stops at 1. Tap plus until it stops: it stops at 10.
  5. With 10 and D20, roll: ten chips, wrapping onto a second row; the total is between 10 and 200 and fits in the circle.
  6. Change the die or quantity without rolling: the caption changes immediately, but the chips and total still show the previous roll. That mismatch is real, and Chapter 7 fixes it by remembering what was actually rolled.

Expected Results

After this chapter, with five D6 rolled, the screen looks similar to this:

Illustrative mockup — not a screenshot

        [dice]  Dice Foundry

   [  D4  ]   [  D6  ]   [  D8  ]      <- D6 orange
   [ D10  ]   [ D12  ]   [ D20  ]

 Number of dice: 5          [ - | + ]

                 .----.
               (   19   )              <- total of the chips
                 '----'
              Rolling 5D6

      [ 4 ] [ 2 ] [ 6 ] [ 1 ] [ 6 ]    <- one chip per die

           [  Roll Dice  ]
Actual iOS Simulator screenshot — three D6 rolled

Figure: three D6 after one roll, with the total 16 in the circle and one tile per die (6, 4 and 6). Your layout is the same with a different count; the numbers you roll will differ on your device.

Checklist of expected behavior:

  • The Stepper ranges from 1 to 10 and its label shows the current number.
  • The caption reads "Rolling" followed by quantity and die with no space between them, such as "Rolling 5D6".
  • After a roll there is one chip per die, and the circle shows their sum.
  • Before the first roll the circle shows 0 and there are no chips.
  • Ten dice wrap onto two rows of chips.

Reading This Like a Developer

Where execution begins. As before: @main DiceFoundryApp creates the window and ContentView. The view's three state properties start as selectedDie = .d6, quantity = 1 and results = []. On the first evaluation of body, total is computed from an empty array and is 0, and ForEach(results.indices, ...) has nothing to iterate.

Which variables hold state. Three @State properties: selectedDie (which die), quantity (how many), and results (the last roll's values). columns and resultColumns are constants. total is derived: it is recomputed from results every time body reads it.

Where values originate and change.

  • selectedDie changes only in the die buttons' action.
  • quantity changes only through the Stepper, via the two-way connection $quantity.
  • results changes only in the Roll Dice action, and only by being replaced as a whole.
  • Each individual die value originates in Int.random(in: 1...sides) inside rollDie(sides:).

Which code runs when Roll Dice is pressed. This is the roll flow at this stage of the app:

Tap "Roll Dice"
   |
   v
Button action closure
   reads quantity (e.g. 3) and selectedDie.sides (e.g. 6)
   |
   v
rollDice(count: 3, sides: 6)
   rolls = []
   for _ in 1...3 ---------> rollDie(sides: 6)
      rolls.append(...)        Int.random(in: 1...6) -> 4, then 2, then 6
   return [4, 2, 6]
   |
   v
results = [4, 2, 6]          (assignment to @State)
   |
   v
SwiftUI notices the change and re-evaluates body
   |
   +--> total -> sum(of: [4, 2, 6]) -> reduce(0, +) -> 12 --> circle shows 12
   +--> caption: "Rolling 3D6"                     (from quantity and selectedDie)
   +--> ForEach(0..<3) -> chips "4", "2", "6"
   |
   v
Screen updated

There is no history and nothing is saved yet: the next roll replaces results, and quitting the app loses everything. Chapter 8 adds history and Chapter 9 saves it.

How the interface responds to state. Each piece of state affects specific parts of body. Changing quantity updates the Stepper label and the caption. Changing selectedDie updates the button tints and the caption. Changing results updates the circle (through total) and the chips. SwiftUI works this out by re-evaluating body and comparing the result with what is on screen; you never update a label directly.

How data passes between pieces of code. Within this one view, data moves through function parameters and return values: the button passes quantity and sides into rollDice, which passes sides to rollDie for each die and returns an array, which is stored in results, which is passed to sum(of:). The Stepper is different: it receives a two-way connection rather than a value, because it must write back.

Business logic versus presentation logic. rollDie, rollDice and sum are business logic: rules about dice that have nothing to do with how the screen looks. They happen to live inside the view for now. The Stepper, grids, chips and caption are presentation logic. Keeping the business logic in small functions with clear inputs and outputs, rather than writing it inside the button closure, is what will make it easy to move into its own type and test it in Chapter 12.

Reading This Like a Developer: Read loops by tracing a tiny input

When you meet a loop you do not understand, pick the smallest interesting input, such as an array of two or three values, and write the variables down after each iteration, as you did in the trace tables in this chapter. It feels slow, but it is the most reliable way to understand any loop, including ones an assistant wrote for you.

Troubleshooting

"Fatal error: Index out of range"

Fatal error: Index out of range

Meaning: the app read or removed an array element at a position that does not exist. This is a runtime crash; the build succeeded.

Likely causes: a loop over 0...array.count instead of 0..<array.count; reading results[index] with an index computed by hand; remove(at:) with an index that is too large; reading results[0] when results is empty.

How to investigate: Xcode stops on the failing line and highlights it. Look at the debug area (⇧⌘Y) to see the values of the variables, especially the index and the array. Ask: what was count, and what index was requested? In Dice Foundry's guided code, results[index] is only used inside ForEach(results.indices, ...), which can only supply valid indexes.

A crash about the range's bounds

The message will be similar to:

Fatal error: Range requires lowerBound <= upperBound

Meaning: a closed range such as 1...count was created with count less than 1, for example 1...0.

Likely causes: the Stepper range was changed to start at 0 (in: 0...10), or rollDice was called with a count of 0.

How to investigate: check the Stepper's in: range and the value passed as count:. Chapter 7 adds explicit validation so the roll button cannot be used with an invalid quantity.

"Cannot find 'result' in scope"

Meaning: some code still refers to the result property deleted in Step 12.

Likely causes: Step 10 or Step 11 was skipped, so the button action or the circle's Text still uses result.

How to investigate: Xcode marks each line that uses result. Compare each with Steps 10 and 11.

"Empty collection literal requires an explicit type"

The message will be similar to:

Empty collection literal requires an explicit type

Meaning: you wrote var rolls = [] or @State private var results = []. Swift cannot work out what the empty array should contain.

How to fix: add the annotation: var rolls: [Int] = [].

"Cannot use mutating member on immutable value"

The message will be similar to "Cannot use mutating member on immutable value: 'rolls' is a 'let' constant".

Meaning: you called append, remove(at:) or another changing method on an array declared with let.

How to fix: declare the array with var if it must change.

The Stepper does not compile or does not change the number

Likely causes:

  • value: quantity without the $. The Stepper needs a two-way connection; a plain value cannot be written back. The compiler reports that it cannot convert an Int to a Binding<Int>, or similar.
  • quantity is missing @State, so $quantity does not exist.

How to investigate: compare the line with Step 6 character by character, including $ and the in: label.

The total does not match the chips

Likely causes: in the loop version, the accumulator was declared inside the loop (so it restarts at 0 every iteration and only the last value survives), or total = value was written instead of total += value. In the reduce version, a starting value other than 0.

How to investigate: trace the loop on paper with a three-element array, as in this chapter's tables, or temporarily add print(total) inside the loop and watch the console.

The caption shows a space, or the wrong text

If the caption reads "Rolling 3 D6", there is a space between \(quantity) and \(selectedDie.name). Dice notation has no space. If it reads "Rolling quantityD6", the backslash and parentheses of the interpolation are missing.

Duplicate-ID warnings or chips that behave oddly

If you wrote ForEach(results, id: \.self), two dice with the same value share an ID. SwiftUI may log a warning in the console about duplicate IDs, and chips may display incorrectly. Use ForEach(results.indices, id: \.self) and read results[index] instead.

Knowledge Check

  1. Why does @State private var results: [Int] = [] need the : [Int] annotation, while let columns = [GridItem(.flexible()), ...] does not?
  2. An array has five elements. What are its first and last valid indexes? What happens if code reads index 5, and is that a compile-time or runtime error?
  3. When would you choose 1...count and when 0..<count? Give an example of an off-by-one bug that comes from choosing the wrong range.
  4. Explain the difference between summing with a for loop and summing with values.reduce(0, +). What does each argument of reduce mean, and what would reduce return for an empty array?
  5. Why is total a computed property instead of a second @State variable updated after each roll? Why does the Stepper receive $quantity rather than quantity?

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 these on a Git branch so your guided project stays identical to the reference (git switch -c challenge-06, then git switch main before Chapter 7). Progressive hints are in the Chapter 6 Exercises document; full solutions are in the Chapter 6 Answers document.

Challenge: Challenge 1 — Average per die

Show the average value of the dice in the latest roll, with one decimal place, under the caption: for example, after rolling 4, 2 and 6, "Average: 4.0". Before the first roll, it must show "Average: 0.0", and the app must never show "nan" or crash. Use a computed property and only concepts from Chapters 1 to 6.

Challenge: Challenge 2 — Show the arithmetic

Under the result chips, show how the total was calculated, for example "4 + 2 + 6" after rolling three dice, or just "5" after rolling one. Before the first roll, show nothing. Write a function that builds this text with a for loop.

Chapter Completion Checklist

  • I can create arrays with a literal, an empty literal plus annotation, [Int]() and Array(repeating:count:).
  • I practised append, remove(at:), removeLast() and removeAll() in the playground and predicted the results.
  • I can explain why indexes start at 0 and what "Index out of range" means.
  • I can write a for … in loop over an array and over a range, and explain _.
  • I can explain the difference between 1...count and 0..<count.
  • ContentView has quantity and results state, and the old result property is gone.
  • The Stepper limits the quantity to 1 through 10, and I can explain $quantity as a two-way connection.
  • rollDice(count:sides:) builds an array with a loop and append.
  • I wrote sum(of:) as a loop, ran it, and then replaced the body with values.reduce(0, +).
  • I can explain reduce(0, +) token by token and expand it back into a loop.
  • total is a computed property, and I can explain why it is not stored.
  • The result chips use ForEach(results.indices, id: \.self), and I can explain why id: \.self is needed.
  • Rolling 1 to 10 of any die shows every value and the correct total.
  • I committed and tagged my work.

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 6: Roll multiple dice and show each result and the total"
git tag chapter-06

Before committing, make sure sum(of:) uses values.reduce(0, +), so your project matches the reference.

To compare with the reference, open Reference-Checkpoints/Checkpoint-06-Multiple-Dice/DiceFoundry/ and compare ContentView.swift with yours (DieType.swift does not change in this chapter). You can use FileMerge (Xcode → Open Developer Tool → FileMerge) or Terminal:

diff -u Reference-Checkpoints/Checkpoint-06-Multiple-Dice/DiceFoundry/ContentView.swift \
  /path/to/your/DiceFoundry/DiceFoundry/ContentView.swift

Differences in comments or the file header are fine, and SwiftPractice.swift is not part of the reference. Differences in code are worth understanding.

Prediction Answers

Arrays playground. The canvas shows:

true 0
[4, 2, 6]
3
4 6
[4, 5, 6]
[] [0, 0, 0]

The array starts empty (isEmpty is true, count is 0). Three appends add values at the end in order. Index 0 is the first value (4) and index 2 is the third (6). Assigning to rolls[1] replaces the 2 with 5. [Int]() is another way to write an empty array, and Array(repeating: 0, count: 3) creates three zeros.

Removing values. remove(at: 1) removes the element at index 1, which is 2, and returns it, so removed is 2 and rolls is [4, 6, 3, 1]. The values after it shifted down: 6 is now at index 1. removeLast() removes 1, leaving [4, 6, 3]. removeAll() leaves [], and isEmpty is true. The canvas shows:

2 [4, 6, 3, 1]
[4, 6, 3]
[] true

Trace the loop sum. For [5, 1, 3, 6], the local total is 0 before the loop, then 5, 6, 9 and 15 after the four iterations. sum(of:) returns 15, the computed total property returns 15, and the circle shows 15.