Chapter 5 Answers — Enumerations and Dice Selection
Knowledge Check Answers
1. Bugs prevented by an enum.
Any two of these, among others: a misspelling such as "D7" or "D 20" that matches no real die; a capitalization mismatch such as "d6" compared with "D6", which is silently false; a missing or failed conversion from text to a number of sides before rolling. With an enum, selectedDie can only hold one of the six declared cases. A misspelled case such as .d7 or .D6 is a compile-time error, so the bug never reaches a running app. And the number of sides comes from sides, with no text parsing at all.
2. Raw value versus computed property.
A raw value is a fixed value attached to each case when you declare it (case d20 = 20); it is part of the enum's definition. A computed property is code that produces an answer every time it is read (var sides: Int { rawValue }); it stores nothing. The app calls rollDie(sides: selectedDie.sides) because sides names the domain concept the function needs. rawValue is a storage detail. If the two ever differed, only sides would need to change, and the call site would stay correct and readable.
3. Raw-value initializer.
DieType(rawValue: 12) produces an optional containing .d12. DieType(rawValue: 13) produces nil, because no case has the raw value 13. The type is DieType? because the initializer cannot guarantee that every possible Int matches a case, so it must be able to say "no such die".
4. CaseIterable and Identifiable.
CaseIterable provides DieType.allCases, the collection that ForEach walks to build one button per die. Without it, there is no allCases and you would have to type the list of cases by hand. Identifiable provides a stable id for each element, which ForEach uses to keep track of which view belongs to which die when the screen updates. Without it, ForEach(DieType.allCases) does not compile (you would have to supply an identity yourself, as you will in Chapter 6).
5. From tap to highlight.
The D8 button's action closure runs selectedDie = dieType, storing .d8. Because selectedDie is @State, SwiftUI notices the change and evaluates body again. ForEach rebuilds its six buttons; each evaluates dieType == selectedDie ? .orange : .gray, which is now true only for D8. The caption evaluates selectedDie.name and produces "Rolling a D8". SwiftUI compares the result with what is on screen and redraws only the changes. The only line you wrote that changes the highlight is the assignment selectedDie = dieType; the .tint ternary describes how it looks for any value.
Challenge Solutions
Challenge 1 — Show the average roll
File: DieType.swift · Where: inside enum DieType, after the name property · Action: Add
var averageRoll: Double {
Double(sides + 1) / 2
}
File: ContentView.swift · Where: in body, directly after the Text("Rolling a \(selectedDie.name)") caption and its .foregroundStyle(.secondary) line, with a blank line before it · Action: Add
Text("Average roll: \(selectedDie.averageRoll)")
.font(.footnote)
.foregroundStyle(.secondary)
Why it works: each face from 1 to N is equally likely, so the average is the midpoint of 1 and N, which is (N + 1) / 2. sides + 1 is an Int; wrapping it in Double(...) converts it before the division, so Double(7) / 2 is 3.5. If you wrote (sides + 1) / 2, integer division would give 3 for a D6, and converting afterwards (Double((sides + 1) / 2)) would still give 3.0. The 2 is a literal, and Swift infers it as a Double because the left side is a Double. Because the property is computed from sides, it works for every die, including any added later, and the text updates as soon as selectedDie changes, because body reads it.
Interpolating a Double shows 3.5, 10.5 and so on. All six averages end in .5, so no extra formatting is needed here. (Chapter 6's challenge shows a way to control decimal places.)
Alternatives: you could name the property average or expectedValue. You could compute it in the view instead (Double(selectedDie.sides + 1) / 2), but it is a fact about the die, so it belongs in DieType where any screen can reuse it.
Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Folder: challenge-solutions/ch05-average/.
Challenge 2 — A bolder picker
File: ContentView.swift · Where: the columns property · Action: Replace (remove one GridItem)
let columns = [
GridItem(.flexible()),
GridItem(.flexible())
]
File: ContentView.swift · Where: inside the label: closure of the die button · Action: Replace the Text and its modifiers
Text(dieType.name)
.font(dieType == selectedDie ? .title2 : .headline)
.fontWeight(dieType == selectedDie ? .heavy : .regular)
.frame(maxWidth: .infinity)
Why it works: LazyVGrid creates one column per GridItem, so two items give two columns and six buttons fill three rows. Each ternary produces a single value of one type: both branches of the first are Font values, and both branches of the second are font weights. Because both are evaluated inside ForEach on every body evaluation, only the button whose dieType equals selectedDie gets the larger, heavier label. .frame(maxWidth: .infinity) stays on the label so every button still fills its column.
Alternatives: you could use .bold(dieType == selectedDie), which takes a Bool directly, instead of the weight ternary. You could also adjust the grid's spacing. A ternary between .buttonStyle(.bordered) and .buttonStyle(.borderedProminent) does not compile, because the two styles are different types; that restriction is why the guided project varies only the tint.
Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Folder: challenge-solutions/ch05-highlight/.
Extra Practice Answers
Exercise A — Predict the output
D12 12
true
D4
true
second is an optional containing .d12; comparing it with first using == is allowed and is true. DieType(rawValue: 3) is nil, so ?? .d4 supplies .d4, whose name is "D4". allCases follows declaration order, so its first element is .d4. (first on a collection is itself optional, which is why the comparison still works: Swift compares an optional DieType with .d4.)
Exercise B — Spot the bug
let selectedDie = dieType inside the action creates a brand-new local constant that exists only inside the closure and disappears immediately. It shadows the @State property of the same name instead of changing it. The state never changes, so the tint comparison never sees a new value. Fix: write selectedDie = dieType with no let. (Xcode also warns that the local constant is never used, which is a useful clue.)
Exercise C — Spot the bug
case 8 = 8: a case name cannot start with a digit. It should becase d8 = 8.case d10 = 6: the raw value 6 is already used byd6, and raw values must be unique. It should becase d10 = 10.
There is also a third problem that appears once those are fixed: the enum declares Identifiable but has no id property, so it does not conform to the protocol. Add var id: Int { rawValue }.
Exercise D — Small modification
File: ContentView.swift · Where: the caption Text · Action: Replace
Text("Rolling a \(selectedDie.name) (1 to \(selectedDie.sides))")
String interpolation can include several expressions; sides supplies the highest face. Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target), in a scratch copy of Checkpoint 05.