Chapter 5 — Enumerations and Dice Selection
At the end of Chapter 4, Dice Foundry rolls a real random number when you tap the button, but it only knows one kind of die: the six-sided D6, hard-coded as rollDie(sides: 6). Tabletop players use six standard dice: D4, D6, D8, D10, D12 and D20. In this chapter you teach the app about all six. You will model them with a Swift enumeration, a type that lists every allowed value in one place, and you will build a grid of buttons that lets the player choose a die. The selected die is highlighted, the caption names it, and the Roll Dice button rolls it. Along the way you meet several ideas that appear in almost every SwiftUI screen: computed properties, ForEach for building repeated views from data, equality comparisons, selection state, conditional styling with the ternary operator, and grid layout.
Learning Objectives
By the end of this chapter you will be able to:
- Explain what an enumeration is and why it is a better model for "one of six dice" than strings or plain integers.
- Declare an
enumwith cases and give each case an integer raw value. - Create an enum value from a raw value and explain why the result is optional.
- Add computed properties to a type and explain how they differ from stored values.
- Use
CaseIterableandallCasesto get every case of an enum in declaration order. - Explain what
Identifiablepromises and whyForEachneeds it. - Use
ForEachto build one view for each element of a collection. - Compare two values with
==and explain the difference between=and==. - Store the user's current choice in
@State(selection state) and use it to drive both behavior and appearance. - Read and write the ternary conditional operator
condition ? a : band use it for conditional styling. - Lay out views in a grid with
LazyVGridandGridItem. - Use the
Button { } label: { }form with multiple trailing closures, and explain why a label can be wider than a simple title button. - Create a new Swift file in Xcode and make sure it belongs to the app target.
Concept Explanation
The problem: a value that must be one of a fixed set
So far the only die your app understands is a number, 6, passed straight into rollDie(sides:). Now the player needs to choose among six dice, and the app needs to remember which one is chosen. How should that choice be represented in code?
There are a few tempting options. Here are two you will see often in quick prototypes and in AI-generated code.
Option 1: a string.
@State private var selectedDie = "D6"
Strings are easy to read, but the compiler knows nothing about which strings are valid. All of these compile without complaint:
selectedDie = "D7" // no such die
selectedDie = "d6" // lowercase, so "d6" == "D6" is false
selectedDie = "D 20" // stray space
selectedDie = "Twenty" // a different spelling entirely
Every one of these is a bug that the compiler cannot catch. Worse, to roll the die you must turn the string back into a number of sides, which means parsing text ("D20" → 20) and deciding what to do when the parse fails. That is extra code and an extra failure path for no benefit.
Option 2: an integer.
@State private var selectedSides = 6
An integer is closer, because the number of sides is what rollDie needs. But Int allows about eighteen quintillion values, and only six of them are real dice. Nothing stops selectedSides = 7, selectedSides = 0, or selectedSides = -3. If 0 ever reaches Int.random(in: 1...sides), the range 1...0 is invalid and the app crashes. And there is no single place in the code that lists "the dice this app supports". To build six buttons you would type [4, 6, 8, 10, 12, 20] somewhere, and if you later add a die you must hunt for every copy of that list.
Option 3: an enumeration. An enumeration (or enum) is a type that defines a fixed list of possible values, called cases. You declare it once:
enum DieType {
case d4
case d6
case d8
case d10
case d12
case d20
}
Now a variable of type DieType can hold exactly one of those six cases and nothing else. selectedDie = .d7 does not compile, because there is no case d7. Misspellings are compile-time errors, not runtime surprises. Xcode's autocomplete lists the valid cases as you type. And because the type itself is the list, the compiler can hand you "all the cases" whenever you need them, for example to build one button per die.
Think of a configuration field that only accepts small, medium or large instance sizes. A schema validator rejects mediun before deployment instead of letting it fail in production. An enum gives you that validation for free, inside the code itself, every time you build. A plain string is like an unvalidated free-text field in a config file: it works until someone makes a typo.
The rule of thumb is simple. When a value must be one of a small, known, fixed set of options, model it as an enum. Dice types, card suits, days of the week, sort orders, and app screens are all good candidates.
Raw values: attaching a number to each case
An enum case is a value in its own right; it does not need to be a number. But our dice have a natural number attached: the number of sides. Swift lets you give each case a raw value of a single type by writing that type after the enum name:
enum DieType: Int {
case d4 = 4
case d6 = 6
}
Now DieType.d6.rawValue is 6. Raw values have three properties worth remembering:
- Every case has one, and they must all be the same type (here,
Int). - They must be unique. Two cases cannot both have the raw value
6. - They are fixed when you write the code. A raw value is not something you change while the app runs.
Raw values also work in the other direction. You can ask the enum to find the case for a raw value:
let die = DieType(rawValue: 8) // DieType? containing .d8
let none = DieType(rawValue: 7) // nil: there is no 7-sided case
The result is an optional, DieType?, because the number you pass might not match any case. You met optionals in Chapter 2: an optional either contains a value or is nil, and you unwrap it with if let or provide a fallback with ??. Dice Foundry does not need this direction yet, but you will see it in other code, especially when values come back from storage or a network, and in Chapter 9 our saved roll history stores dice by their raw values.
Computed properties: answers derived from what you already have
The rest of the app does not really want "a raw value". It wants answers to questions such as "how many sides does this die have?" and "what should the button say?". You add those answers as computed properties:
var sides: Int {
rawValue
}
A computed property looks like a variable from the outside (selectedDie.sides), but it does not store anything. Each time you read it, Swift runs the code between the braces and gives you the result. Because the body is a single expression, Swift returns that expression automatically; you do not need to write return. (You saw the same rule with body in Chapter 3: body is a computed property too.)
Why have both rawValue and sides if they are the same number? Because they mean different things. rawValue is a storage detail: "the integer this case is associated with". sides is a domain concept: "how many faces the die has". Code that says rollDie(sides: selectedDie.sides) reads correctly to anyone. If one day you added a die whose raw value was not its side count, you would change sides in one place and every caller would still be right.
The name property builds the text shown on buttons and in the caption:
var name: String {
"D\(rawValue)"
}
This uses string interpolation from Chapter 2: for .d20 the result is "D20".
An enum value is just "which case it is" (plus its raw value). You cannot add var color = "red" as a stored property inside an enum. You can add as many computed properties as you like, because they derive their answers from the case. Chapter 8 introduces struct types that hold their own stored data.
Protocols you adopt: CaseIterable and Identifiable
In Chapter 3 you wrote struct ContentView: View. The : View part declared that ContentView conforms to the View protocol: it promises to provide a body. Enums can conform to protocols too, and DieType adopts two very useful ones.
CaseIterable asks the compiler to generate a static list of every case, named allCases, in the order you declared them:
DieType.allCases // [.d4, .d6, .d8, .d10, .d12, .d20]
You write nothing except the word CaseIterable. That list is what lets you build six buttons without typing six buttons. When a future chapter adds a die, the button grid picks it up automatically, because the grid is built from allCases.
Identifiable is a promise that every value has a stable, unique identity, exposed as a property named id. SwiftUI uses identity to keep track of which on-screen view belongs to which piece of data, so that when data changes it can update, insert or remove exactly the right views. For DieType, the raw value is already unique, so it makes a perfect identity:
var id: Int {
rawValue
}
Unlike CaseIterable, the compiler cannot guess what your identity should be, so you provide id yourself. If you declare Identifiable and forget id, the build fails with an error saying the type does not conform to the protocol.
The final declaration line lists the raw value type first, then the protocols, separated by commas:
enum DieType: Int, CaseIterable, Identifiable {
Equality: = versus ==
To highlight the selected die, the app must ask, for each button, "is this the selected die?". That is an equality comparison, written with two equals signs:
dieType == selectedDie // true or false (a Bool)
You met comparison operators in Chapter 2. It is worth restating the difference that trips up everyone at least once:
| Operator | Name | Meaning | Result |
|---|---|---|---|
= |
assignment | Store the value on the right into the variable on the left | nothing (it is a statement) |
== |
equality | Are these two values the same? | a Bool |
Enums without extra data get == automatically. Two DieType values are equal when they are the same case.
Selection state
In Chapter 4 you learned that @State holds a value the view owns, and that changing it makes SwiftUI recompute body. A selection is simply state that records which of several options the user has chosen:
@State private var selectedDie: DieType = .d6
This single variable now drives three things:
- Behavior: the Roll Dice button rolls
selectedDie.sides. - Text: the caption shows
selectedDie.name. - Appearance: each die button compares itself with
selectedDieand colors itself accordingly.
Tapping a die button does only one thing: it assigns a new case to selectedDie. Everything else follows because SwiftUI re-runs body and every expression that reads selectedDie produces a new answer. You never write code that says "turn the old button gray and the new button orange". You describe what the screen should look like for any value of selectedDie, and SwiftUI keeps the screen in step with the state.
This is the same model as a declarative infrastructure tool. You do not issue "remove server A from the pool, add server B" commands. You change one value in the desired-state file and the reconciler works out what changed. Here selectedDie is the value, body is the manifest, and SwiftUI is the reconciler.
The ternary conditional operator
Each die button needs one of two tint colors depending on a Bool. Swift's ternary conditional operator chooses between two values in a single expression:
condition ? valueIfTrue : valueIfFalse
It is called "ternary" because it takes three parts. In Dice Foundry:
.tint(dieType == selectedDie ? .orange : .gray)
Read it aloud as: "if this button's die equals the selected die, then orange, otherwise gray". Both branches must produce the same type, here a Color. The ternary is an expression: it produces a value you can pass directly as an argument. That is why it fits neatly inside a modifier. Chapter 7 introduces if and else statements for cases where you need to choose between larger blocks of code; the ternary is for choosing between two values.
ForEach: views from data
ForEach is a SwiftUI view that takes a collection and a closure, and builds the closure's views once for each element:
ForEach(DieType.allCases) { dieType in
Text(dieType.name)
}
This produces six Text views: "D4", "D6", "D8", "D10", "D12", "D20". Inside the closure, dieType is the current element. Remember closures from Chapter 4: { dieType in ... } is a closure with one parameter, named dieType, and the code after in is its body.
ForEach requires each element to be identifiable so SwiftUI can tell the six views apart when state changes. Because DieType is Identifiable, ForEach reads each case's id automatically. In Chapter 6 you will meet the other form, where you tell ForEach which property to use as the identity.
ForEach looks like a loop, and it does run its closure once per element, but it is a view. It describes "one of these per element" so SwiftUI can create and update the views. Chapter 6 introduces Swift's for loop, which is an ordinary statement you use inside functions. You cannot use a for loop directly inside body to make views; you use ForEach.
Grids: LazyVGrid and GridItem
Six buttons in one row would be cramped on a phone, and six in a column would waste space. A grid of two rows of three is just right. SwiftUI's LazyVGrid arranges views into columns that grow downward (V for vertical). You describe the columns with an array of GridItem values:
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
Three GridItems means three columns. .flexible() means "share the available width". Six views laid into three columns become two rows of three. The word "lazy" means the grid only creates views as they are about to appear on screen, which matters for long scrolling grids and makes no visible difference for six buttons.
The square brackets with comma-separated values are an array literal: a list of values written directly in code. Chapter 6 is all about arrays. For now, read [a, b, c] as "a list containing a, b and c".
Buttons with a custom label
In Chapters 3 and 4 you wrote buttons like this:
Button("Roll Dice") {
result = rollDie(sides: 6)
}
That form takes a title string and an action closure. SwiftUI builds the label for you. It is perfect for simple buttons, but you cannot style the label itself, for example to make it stretch to fill a grid column.
The other form takes two closures: one for the action and one that builds the label view:
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
This is multiple trailing closure syntax. The first trailing closure is written right after Button with no label; it is the action. Each later trailing closure is introduced by its argument label followed by a colon, here label:. It is equivalent to the longer form Button(action: { ... }, label: { ... }), which you will occasionally see in older code.
Why does the label need .frame(maxWidth: .infinity)? A bordered button draws its background around its label. With a title-only button, the label is only as wide as the text, so "D4" makes a narrow button and "D20" a wider one, and the grid looks uneven. Putting .frame(maxWidth: .infinity) on the label tells the text "take all the width your grid column offers". The button's border is then drawn around that full-width label, and all six buttons are the same width. The frame has to be on the label because the label is what the border wraps; a frame on the outside of the button would make the space bigger but leave the visible button the same size.
import Foundation versus import SwiftUI
When you create a new Swift file, Xcode starts it with import Foundation. ContentView.swift starts with import SwiftUI. The difference:
- Foundation is Apple's base library of non-visual building blocks: dates, URLs, file access, number and date formatting, JSON encoding, and much more. It is not tied to any user interface.
- SwiftUI is the user interface framework. Importing it also makes Foundation available.
DieType describes dice; it draws nothing on screen. So its file imports Foundation, not SwiftUI. Strictly, the enum as written only uses Swift's built-in standard library (Int, String, the protocols), so it would compile with no import at all. We keep the template's import Foundation because it is the normal starting point for a model file and because later chapters add Foundation features. The habit to build is: model files do not import SwiftUI. A model that needs SwiftUI is usually doing presentation work that belongs in a view.
AI assistants frequently generate "stringly typed" code such as @State var mode = "easy" and later compare if mode == "Easy", which silently never matches. When you see a string or integer used to choose among a fixed set of options, ask the assistant to "replace this with an enum with a case for each option, and add computed properties for display text". Also watch for the opposite mistake: an enum that duplicates data that already exists elsewhere, or a switch over every case to return a number that could simply be a raw value. A good enum has one obvious list of cases and small, clearly named computed properties.
Syntax Breakdown
The enum declaration
enum DieType: Int, CaseIterable, Identifiable {
| Token | Meaning |
|---|---|
enum |
Keyword: declare a new enumeration type. |
DieType |
The type's name. Type names start with an uppercase letter (UpperCamelCase). |
: |
Begins the list of things this type is based on or conforms to. |
Int |
The raw value type. It must come first in the list. Every case gets an Int raw value. |
, |
Separates entries in the list. |
CaseIterable |
Protocol: the compiler generates DieType.allCases. |
Identifiable |
Protocol: the type promises an id property that uniquely identifies each value. |
{ |
Opens the enum's body, which contains its cases and properties. |
A case with a raw value
case d4 = 4
| Token | Meaning |
|---|---|
case |
Keyword: declare one possible value of the enum. |
d4 |
The case name. Case names start with a lowercase letter (lowerCamelCase). |
= |
Here it means "has the raw value", not assignment at run time. |
4 |
The raw value: an Int literal, because the enum's raw type is Int. |
Case names cannot start with a digit, so 4 or 4d would not be valid names. That is why the cases are d4, d6 and so on, and the display text "D4" comes from name.
A computed property
var name: String {
"D\(rawValue)"
}
| Token | Meaning |
|---|---|
var |
Computed properties are always declared with var, even though you cannot assign to this one. |
name |
The property's name. |
: String |
The property's type. Required for computed properties. |
{ ... } |
The code that computes the value. It runs every time the property is read. |
"D\(rawValue)" |
A single expression, so it is returned automatically. rawValue here means "the raw value of the case this property is being read on". |
Referring to a case: full and shorthand
let a = DieType.d6 // full form: Type.case
let b: DieType = .d6 // shorthand: the type is already known
@State private var selectedDie: DieType = .d6
The leading dot form .d6 is called an implicit member expression. It works only when Swift already knows which type is expected. In @State private var selectedDie: DieType = .d6, the annotation : DieType tells the compiler the type, so .d6 can only mean DieType.d6. This is type inference from Chapter 2 working in the other direction: instead of inferring the variable's type from the value, Swift uses the declared type to understand the value. You already relied on this with .orange, .title and .borderedProminent: each is shorthand for a member of the type that the modifier expects.
If there is no annotation, the shorthand fails:
let die = .d6 // error: Swift cannot tell which type .d6 belongs to
The ternary operator
.tint(dieType == selectedDie ? .orange : .gray)
| Token | Meaning |
|---|---|
dieType == selectedDie |
The condition, a Bool. |
? |
"If the condition is true, the result is..." |
.orange |
The value used when the condition is true. |
: |
"...otherwise, the result is..." |
.gray |
The value used when the condition is false. |
.tint expects a Color, so Swift infers that .orange and .gray mean Color.orange and Color.gray.
ForEach over an Identifiable collection
ForEach(DieType.allCases) { dieType in
...
}
| Token | Meaning |
|---|---|
ForEach |
A SwiftUI view that builds views from a collection. |
DieType.allCases |
The collection: all six cases, from CaseIterable. |
{ dieType in |
A trailing closure with one parameter. dieType is the current element. You choose its name. |
... |
The views to build for this element. |
LazyVGrid
LazyVGrid(columns: columns, spacing: 12) {
...
}
| Token | Meaning |
|---|---|
LazyVGrid |
A container that lays out its children in a vertical grid. |
columns: |
Argument label. The grid's column definitions. |
columns |
Our property: an array of three GridItems. The label and the property happen to share a name. |
spacing: 12 |
Vertical space in points between rows. |
{ ... } |
Trailing closure containing the grid's content. |
Button with multiple trailing closures
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
}
| Token | Meaning |
|---|---|
Button { |
The first trailing closure: the action, run when tapped. Its label is omitted. |
selectedDie = dieType |
Assignment: store this button's die in the selection state. |
} label: { |
Close the action closure, then open the second trailing closure, introduced by its label label:. |
Text(dieType.name) |
The view that is the button's visible content. |
Guided Implementation
You will create the DieType enum in its own file, explore it briefly, connect it to ContentView through a new state variable, and then build the grid of die buttons. The project builds after every step.
Start from your completed Chapter 4 project. If you want to be sure your starting point matches, compare ContentView.swift with Reference-Checkpoints/Checkpoint-04-State-and-Random/DiceFoundry/ContentView.swift.
Step 1 — Create the DieType.swift file
File: DieType.swift (new) · Where: the DiceFoundry folder in the Project navigator · Action: Create file
- In the Project navigator (⌘1 if it is hidden), click the yellow
DiceFoundryfolder that containsContentView.swift. New files are created next to the selected item, so this puts the file in the right place. - Choose File → New → File from Template... (⌘N).
- In the template chooser, make sure iOS is selected at the top, then choose Swift File (not "SwiftUI View") and click Next.
- In the save dialog, type the name
DieType. Xcode adds.swift. - Look at the Targets list in the dialog. Make sure DiceFoundry is checked. This is called target membership: it tells Xcode to compile this file into the app. A file that is not a member of the app target is ignored by the build, and
ContentViewwould not be able to seeDieType. - Click Create.
Recent Xcode versions call this command File from Template...; older versions call it File.... The template may also be listed under a "Source" heading. The goal is the same: a plain Swift file, named DieType.swift, in the app target.
Xcode opens the new file. It contains a comment header and one line of code, similar to this:
//
// DieType.swift
// DiceFoundry
//
// Created by Your Name on 12/5/26.
//
import Foundation
The header is only a comment; yours will show your name and the date, and the reference checkpoint uses a shorter header. Leave import Foundation in place. As explained in the Concept Explanation, a model file imports Foundation, not SwiftUI.
If you ever need to check or fix target membership later, select the file in the Project navigator, open the File inspector (⌥⌘1, or ⌥⌘0 to show the inspector panel), and look at Target Membership.
What next: build with ⌘B. An empty file with an import builds without problems.
Step 2 — Declare the enum and its cases
File: DieType.swift · Where: below import Foundation, after one blank line · Action: Add
Type this:
enum DieType: Int {
case d4 = 4
case d6 = 6
case d8 = 8
case d10 = 10
case d12 = 12
case d20 = 20
}
What it does: declares a new type, DieType, with exactly six possible values. Each case carries an Int raw value equal to the number of sides.
Why it is written this way: one case per line, in increasing order, makes the list easy to scan and controls the order of allCases later (and therefore the order of the buttons). The raw values are explicit so that a reader sees immediately which number belongs to which die. You will add more to the first line in Step 4, so this version of the line is temporary.
What next: build with ⌘B. The build should succeed. Nothing in the app uses DieType yet.
While you are defining the cases, autocomplete has nothing to offer. But in Step 7, when you type the dot after =, Xcode will list d4, d6 and the rest. That is one of the everyday benefits of an enum over strings.
Step 3 — Add the sides and name properties
File: DieType.swift · Where: inside enum DieType, after case d20 = 20 and one blank line, before the closing brace · Action: Add
var sides: Int {
rawValue
}
var name: String {
"D\(rawValue)"
}
What it does: gives every die two derived answers. DieType.d20.sides is 20; DieType.d20.name is "D20".
Why it is written this way: the rest of the app asks domain questions ("how many sides?", "what is it called?") instead of reaching for rawValue directly. Each body is one expression, so no return is needed. Both properties are var because computed properties must be declared with var; you still cannot assign to them, because they have no setter.
What next: build with ⌘B. It should succeed.
Step 4 — Add an identity
File: DieType.swift · Where: inside enum DieType, after the cases and one blank line, before var sides · Action: Add
var id: Int {
rawValue
}
What it does: gives each case a unique identifier. Raw values are guaranteed unique, so they are a safe identity.
Why it is placed first: by convention id comes before other properties, because it is what Identifiable asks for. You add it before declaring Identifiable in the next step, so the project still builds in between.
What next: build with ⌘B. It should succeed.
Step 5 — Adopt CaseIterable and Identifiable
File: DieType.swift · Where: the line enum DieType: Int { · Action: Replace
Before:
enum DieType: Int {
After:
enum DieType: Int, CaseIterable, Identifiable {
What it does: CaseIterable makes the compiler generate DieType.allCases. Identifiable declares that the type provides an id, which you added in Step 4.
Why it is written this way: the raw value type must come first after the colon; protocols follow in any order. These two protocols are exactly what ForEach needs to build one button per die.
Your complete file should now look like this (your header comment may differ):
//
// DieType.swift
// DiceFoundry
//
import Foundation
enum DieType: Int, CaseIterable, Identifiable {
case d4 = 4
case d6 = 6
case d8 = 8
case d10 = 10
case d12 = 12
case d20 = 20
var id: Int {
rawValue
}
var sides: Int {
rawValue
}
var name: String {
"D\(rawValue)"
}
}
What next: build with ⌘B. It should succeed. Try an experiment: temporarily delete the id property and build again. You should get an error similar to "Type 'DieType' does not conform to protocol 'Identifiable'". Undo (⌘Z) to restore it and build again.
Step 6 — Explore DieType in a playground
This step is practice, not project code. It lets you see the enum's behavior before you wire it into the interface.
File: SwiftPractice.swift · Where: at the end of the file · Action: Add
If you kept SwiftPractice.swift from Chapter 2, open it and add the block below at the end. If you deleted it, create it again the same way you created DieType.swift in Step 1 (name it SwiftPractice), and replace import Foundation with import Playgrounds.
#Playground("Exploring DieType") {
let favorite = DieType.d20
print(favorite)
print(favorite.rawValue)
print(favorite.sides)
print(favorite.name)
print(DieType.allCases.count)
let fromNumber = DieType(rawValue: 8)
print(fromNumber ?? .d6)
let missing = DieType(rawValue: 7)
print(missing == nil)
print(favorite == .d20)
print(favorite == .d6)
}
Write down what each of the nine print lines will show. Pay special attention to print(favorite), print(fromNumber ?? .d6) and the two comparisons at the end. The answers are in Prediction Answers at the end of the chapter.
Open the canvas (⌥⌘↩) if it is not visible and select the "Exploring DieType" playground to see the results. Because SwiftPractice.swift belongs to the app target, the playground can use DieType directly.
Why this matters: you have now seen every enum feature the app relies on: a case, its raw value, its computed properties, allCases, raw-value lookup returning an optional, and equality.
What next: build with ⌘B. The playground does not change the app.
Step 7 — Add the selection state
Now switch to ContentView.swift.
File: ContentView.swift · Where: inside struct ContentView, directly after @State private var result: Int = 0 · Action: Add
@State private var selectedDie: DieType = .d6
What it does: adds a second piece of state that records which die is selected. It starts as the D6, so the app behaves exactly as before until the player chooses something else.
Why it is written this way: @State because the value changes while the app runs and the screen depends on it. private because only this view should change it. The annotation : DieType makes the type explicit and lets you write the shorthand .d6.
What next: build with ⌘B. You may see no warning even though selectedDie is unused; the next steps use it.
Step 8 — Name the selected die in the caption
File: ContentView.swift · Where: in body, below the ZStack with the circle · Action: Replace
Before:
Text("Rolling a D6")
After:
Text("Rolling a \(selectedDie.name)")
Keep the .foregroundStyle(.secondary) line below it unchanged.
What it does: the caption now reads the selection's name instead of a fixed string.
What next: look at the preview. It still says "Rolling a D6", because selectedDie starts as .d6. The difference is that the text is now derived from state.
Step 9 — Roll the selected die
File: ContentView.swift · Where: inside the Button("Roll Dice") action closure · Action: Replace
Before:
result = rollDie(sides: 6)
After:
result = rollDie(sides: selectedDie.sides)
What it does: removes the last hard-coded 6. The function you wrote in Chapter 4 already accepts any number of sides; now it receives the selected die's count.
Why it is written this way: rollDie(sides:) does not need to know about DieType. It just needs a number. The view translates "which die" into "how many sides" at the moment of the call, using the sides property. Keeping rollDie simple means it stays easy to understand and test.
What next: run the app (⌘R). It should behave exactly as in Chapter 4: values from 1 to 6, caption "Rolling a D6". There is no way to change the die yet.
Step 10 — Define the grid columns
File: ContentView.swift · Where: inside struct ContentView, after the two @State lines and one blank line, before var body · Action: Add
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
What it does: describes a three-column layout in which each column takes an equal share of the available width.
Why it is written this way: the layout never changes, so it is a let constant, not state. It lives outside body so that body stays focused on the view hierarchy. Each GridItem on its own line makes the column count obvious at a glance: three lines, three columns. The value is an array literal; Swift infers its type as an array of GridItem. Chapter 6 explains arrays fully.
What next: build with ⌘B. Nothing visible changes yet.
Step 11 — Add a first version of the die grid
This step uses the simple button form so you can see what goes wrong with it. You will replace it in Step 12.
File: ContentView.swift · Where: in body, after the closing brace of the title HStack and one blank line, before the first Spacer() · Action: Add
LazyVGrid(columns: columns, spacing: 12) {
ForEach(DieType.allCases) { dieType in
Button(dieType.name) {
selectedDie = dieType
}
.buttonStyle(.bordered)
}
}
What it does: creates a three-column grid. Inside it, ForEach walks DieType.allCases and builds one bordered button per die. Each button's action assigns its own die to selectedDie.
Note how the closure captures dieType: the D10 button's closure remembers .d10, so tapping it always stores .d10, no matter how much later the tap happens.
What next: run the app (⌘R). You should see two rows of three buttons under the title. Tap D20: the caption changes to "Rolling a D20". Tap Roll Dice a few times and you should see values above 6. Selection works.
Now look closely at the buttons. They are different widths: "D4" is narrower than "D20", and none of them fill their column. Nothing shows which die is selected except the caption. The next two steps fix both problems.
Step 12 — Give each button a full-width label
File: ContentView.swift · Where: inside ForEach, the whole Button(dieType.name) { ... } and its .buttonStyle(.bordered) line · Action: Replace
Replace the button from Step 11 with:
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
What it does: the action is unchanged. The label is now a Text view you control: a headline font, and a frame that expands to the full width of the grid column.
Why it is written this way: .frame(maxWidth: .infinity) belongs on the label because a bordered button draws its rounded background around its label. A full-width label means a full-width button. The two-closure form is the only way to attach modifiers to the label itself.
What next: look at the preview or run the app. All six buttons should now be equal width, filling two neat rows.
Step 13 — Highlight the selected die
File: ContentView.swift · Where: directly after .buttonStyle(.bordered) inside ForEach · Action: Add
.tint(dieType == selectedDie ? .orange : .gray)
What it does: colors each button orange if it is the selected die and gray otherwise.
Why it is written this way: the ternary operator produces a Color value, which is exactly what .tint needs. Because body is recomputed whenever selectedDie changes, every button re-evaluates its comparison, so exactly one button is orange at any moment. Orange matches the Roll Dice button and the title icon, so the color says "this is the active choice".
Your complete grid should now read:
LazyVGrid(columns: columns, spacing: 12) {
ForEach(DieType.allCases) { dieType in
Button {
selectedDie = dieType
} label: {
Text(dieType.name)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(dieType == selectedDie ? .orange : .gray)
}
}
What next: go to the full test in Step 14.
Step 14 — Test every die
Run the app (⌘R) and work through this short manual test:
- On launch, D6 is orange and the caption says "Rolling a D6". The circle shows 0, as in Chapter 4.
- Tap D4. D4 turns orange, D6 turns gray, and the caption says "Rolling a D4". Roll ten times: every value is between 1 and 4.
- Tap D20. Roll until you have seen at least one value above 12. Every value is between 1 and 20.
- Tap each of the other dice in turn and confirm the highlight and caption follow your tap.
- Tap the already-selected die. Nothing changes, which is correct: assigning the same value again leaves the screen the same.
Starting from a fresh launch, the player taps D10, then D4, then D10 again, then Roll Dice. Before running it, answer: what does selectedDie hold after each tap, which button is orange at the end, what does the caption say, and what is the smallest and largest value the roll could produce? Answers are at the end of the chapter.
Expected Results
After this chapter, the screen has a die picker under the title. With D20 selected it looks like this:
Illustrative mockup — not a screenshot
[dice] Dice Foundry
[ D4 ] [ D6 ] [ D8 ] <- gray, bordered
[ D10 ] [ D12 ] [ D20 ] <- D20 is orange
.----.
( 17 ) <- last roll, 1...20
'----'
Rolling a D20
[ Roll Dice ] <- orange, prominent

Figure: D20 selected and not yet rolled, so the circle still shows 0 and the caption reads "Rolling a D20". After you roll, the number in the circle will differ on your device.
Checklist of expected behavior:
- Six equal-width buttons in two rows of three, in the order D4, D6, D8, D10, D12, D20.
- Exactly one button is orange at all times; at launch it is D6.
- The caption always names the selected die.
- Rolls stay within 1 and the selected die's number of sides.
- The circle still shows 0 before the first roll and keeps the last value when you change dice. (The last result does not reset when you pick a new die. That is acceptable for now; Chapter 7 reworks what is shown before and after a roll.)
Reading This Like a Developer
Where execution begins. Nothing has changed at launch: iOS starts the process, @main DiceFoundryApp creates the WindowGroup, and ContentView is created with its @State initial values: result is 0 and selectedDie is .d6. SwiftUI then reads body for the first time.
How the grid is built. While evaluating body, SwiftUI reaches LazyVGrid, reads columns (three flexible columns) and evaluates the ForEach. ForEach reads DieType.allCases, a list generated by the compiler from your declaration order, and runs its closure once per case. Each run produces one Button, and each button's tint is decided right then by comparing that button's dieType with the current selectedDie. ForEach uses each case's id (its raw value) to remember which button is which.
Which code runs when a die button is pressed. Only the action closure of that button: selectedDie = dieType. That single assignment is the whole "selection" feature. Because selectedDie is @State, SwiftUI notices the change and schedules a new evaluation of body.
How the interface responds. During the new evaluation, three expressions read selectedDie: the six tint comparisons, the caption interpolation selectedDie.name, and nothing else on screen. Each produces a new answer, SwiftUI compares the new description with the old one, and only the changed parts are redrawn: two button tints and the caption text. You never wrote code to update them individually.
Which code runs when Roll Dice is pressed. The roll button's closure reads selectedDie.sides (a computed property, which reads rawValue), passes it to rollDie(sides:), which calls Int.random(in: 1...sides). The returned number is assigned to result, which is state, so body is evaluated again and the circle shows the new value.
Tap "D20" Tap "Roll Dice"
| |
v v
selectedDie = .d20 selectedDie.sides -> 20
| |
v v
SwiftUI re-evaluates body rollDie(sides: 20)
| |
+-> tints: D20 orange, v
| others gray Int.random(in: 1...20) -> 17
+-> caption: "Rolling a D20" |
v
result = 17
|
v
SwiftUI re-evaluates body
-> circle shows 17
Which variables hold state. Two: result (the last value rolled) and selectedDie (the current choice). columns is a constant. sides, name and id are computed on demand and store nothing.
Business logic versus presentation logic. DieType is a small piece of business (domain) logic: it defines which dice exist and how many sides each has. It lives in its own file and imports no UI framework. ContentView is presentation: it decides how dice are laid out, which color means "selected", and what the caption says. rollDie(sides:) is business logic that still lives inside the view; Chapter 12 moves dice rolling into its own type, and the reasons will be clearer by then.
When you read unfamiliar SwiftUI code, pick something on screen, such as the caption text, and follow it backward: the Text reads selectedDie.name; name is computed from rawValue; selectedDie is @State, set initially to .d6 and changed only in one button action. In three hops you know every way that text can change. Practise this on any screen you inherit.
Troubleshooting
"Cannot find type 'DieType' in scope"
Cannot find type 'DieType' in scope
Meaning: while compiling ContentView.swift, the compiler found no type named DieType in the app.
Likely causes:
DieType.swiftis not a member of the DiceFoundry target (the checkbox in Step 1 was cleared).- The enum name is spelled differently, for example
enum Dietypeorenum DiceType. Swift names are case-sensitive. - The file was saved somewhere outside the project and never added.
How to investigate: select DieType.swift in the Project navigator and open the File inspector (⌥⌘1). Under Target Membership, make sure DiceFoundry is checked. Then compare the spelling of the enum line with the @State line in ContentView.
The type does not conform to Identifiable
Type 'DieType' does not conform to protocol 'Identifiable'
Meaning: you declared Identifiable but the type does not provide what the protocol requires.
Likely causes: the id property is missing, misspelled (var ID, var identifier), or declared outside the enum's braces.
How to investigate: make sure var id: Int { rawValue } is inside enum DieType { ... }. Xcode may offer a fix-it to add stubs; it is clearer to type the property yourself.
ForEach complains about Identifiable
The message will be similar to:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'DieType' conform to 'Identifiable'
Meaning: ForEach was given a collection whose elements have no identity it can use.
Likely causes: Identifiable is missing from the enum DieType line, even though var id exists. Having an id property is not enough; the type must declare the protocol.
How to investigate: check the declaration line matches enum DieType: Int, CaseIterable, Identifiable {.
"Type 'DieType' has no member 'allCases'"
Meaning: the compiler did not generate allCases.
Likely cause: CaseIterable is missing from the declaration line.
"Raw value for enum case is not unique"
The message will be similar to:
Raw value for enum case is not unique
Meaning: two cases share a raw value. A typical cause is a copy-paste mistake: you copy the case d8 = 8 line, rename the copy to d10, and forget to change its number.
How to investigate: the error points at the duplicate case; compare every raw value with its case name.
Using = where == was intended
.tint(dieType = selectedDie ? .orange : .gray)
The message will be similar to "Cannot assign to value: 'dieType' is a 'let' constant", or a complaint that the expression is not a Bool.
Meaning: a single = is an assignment, not a comparison. Swift does not allow an assignment to be used as a condition, which is a deliberate safety feature.
How to investigate: whenever you see an error about assignment inside a condition, look for a missing second =.
The two sides of a ternary have different types
.tint(dieType == selectedDie ? .orange : "gray")
Meaning: both outcomes of ? : must be the same type. .orange is a Color; "gray" is a String. The compiler reports that it cannot convert one to the other or that the result type is ambiguous.
A related trap: you cannot use a ternary to choose between .buttonStyle(.bordered) and .buttonStyle(.borderedProminent). They are different types, so the compiler rejects the expression even though both look like "a button style". This is why Dice Foundry keeps one style and varies only the tint.
"Cannot infer contextual base in reference to member 'd6'"
@State private var selectedDie = .d6
Meaning: the leading-dot shorthand needs to know the type, but there is no annotation for Swift to use.
How to fix: add the type annotation, @State private var selectedDie: DieType = .d6, or write the full DieType.d6.
The buttons are different widths
Likely causes: .frame(maxWidth: .infinity) is missing, or it is attached outside the label: closure (for example after .buttonStyle(.bordered)), so it enlarges the space around the button instead of the label itself.
How to investigate: make sure the frame modifier is indented under Text(dieType.name) inside the label: braces, then re-indent with ⌃I to check the structure.
Tapping a die does nothing
Likely causes: the action assigns to the wrong variable, the assignment was put in the label: closure instead of the action closure, or selectedDie lost its @State attribute. (Without @State, the compiler reports that it cannot assign to a property because self is immutable.)
How to investigate: check that selectedDie = dieType sits in the first closure, directly after Button {, and that the property declaration starts with @State.
Knowledge Check
- Give two specific bugs that are possible when the selected die is stored as a
Stringsuch as"D6", and explain how an enum prevents each of them. - What is the difference between a raw value and a computed property in
DieType? Why does the app useselectedDie.sidesrather thanselectedDie.rawValuewhen callingrollDie(sides:)? DieType(rawValue: 12)andDieType(rawValue: 13)both compile. What does each produce, and why is the result type optional?- What do
CaseIterableandIdentifiableeach contribute to building the die grid withForEach? What would break without each? - When the player taps the D8 button, list in order what happens from the tap to the screen showing D8 highlighted. Which line of code did you write that changes the highlight?
Independent Challenge
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-05, then git switch main before Chapter 6). Progressive hints are in the Chapter 5 Exercises document; full solutions are in the Chapter 5 Answers document.
Add a computed property to DieType that returns the average result of one roll of that die as a Double (for a D6 the average is 3.5; for a D20 it is 10.5). Display it under the caption in small secondary text, for example "Average roll: 3.5". It must update immediately when the player selects a different die. Do not use a list of six hand-typed averages.
Change the die picker to three rows of two buttons, and make the selected die's label larger and heavier than the others, in addition to the existing orange tint. Use the ternary operator. The buttons must remain equal width.
Chapter Completion Checklist
- I created
DieType.swiftwith File → New → File from Template → Swift File, and it is a member of the DiceFoundry target. - I can explain why an enum is a better model for dice than strings or plain integers.
DieTypehas six cases withIntraw values, plusid,sidesandname.- I can explain the difference between a raw value, a computed property and a stored property.
- I can explain what
CaseIterableandIdentifiableprovide. - I explored
DieTypein a playground and predicted its output, includingDieType(rawValue: 7). ContentViewhas@State private var selectedDie: DieType = .d6, and I can explain why.d6works withoutDieType..- The die picker is a
LazyVGridbuilt withForEach(DieType.allCases). - I can read
Button { } label: { }and explain why the label has.frame(maxWidth: .infinity). - I can read the ternary in
.tint(dieType == selectedDie ? .orange : .gray)aloud. - I can explain the difference between
=and==. - Selecting each die updates the highlight and the caption, and rolls stay within range.
- 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 including the new DieType.swift, enter the message below, and commit. Or in Terminal, from your project folder:
git add -A
git commit -m "Chapter 5: Add DieType enum and dice selection grid"
git tag chapter-05
git add -A is important this time: it stages the new file as well as the changed one. If you run git status before committing, you should see DieType.swift listed as a new file.
To compare with the reference, open Reference-Checkpoints/Checkpoint-05-Dice-Selection/DiceFoundry/ and compare DieType.swift and ContentView.swift with yours. You can use FileMerge (Xcode → Open Developer Tool → FileMerge) or Terminal:
diff -u Reference-Checkpoints/Checkpoint-05-Dice-Selection/DiceFoundry/ContentView.swift \
/path/to/your/DiceFoundry/DiceFoundry/ContentView.swift
Differences in the file header comments are fine. If you kept SwiftPractice.swift, that file is not in the reference checkpoint, which is also fine. Differences in code are worth understanding before you move on.
Prediction Answers
Exploring DieType. The canvas shows, line by line:
d20
20
20
D20
6
d8
true
true
false
print(favorite)prints the case name,d20, not the raw value and not the display name. Printing an enum shows how the case is spelled in code.rawValueandsidesare both20;nameis"D20".allCaseshas six elements.DieType(rawValue: 8)finds.d8, sofromNumberis an optional containing.d8. The?? .d6fallback is not used, andprintshowsd8.DieType(rawValue: 7)finds no case, somissingisnilandmissing == nilistrue.favorite == .d20istrue(same case) andfavorite == .d6isfalse.
Trace a sequence of taps. After tapping D10, selectedDie is .d10. After D4, it is .d4. After D10 again, it is .d10. Each tap replaces the previous value; nothing accumulates. At the end, D10 is the only orange button and the caption reads "Rolling a D10". The roll calls rollDie(sides: 10), which uses Int.random(in: 1...10), so the smallest possible value is 1 and the largest is 10.