Chapter 6 Exercises — Arrays, Loops, and Multiple Dice
These exercises build on the Chapter 6 project. Do them on a separate Git branch so your guided project stays identical to the reference checkpoint:
First commit and tag the guided work using the workbook's Development Checkpoint. Confirm git status --short prints nothing, then create the branch:
git switch -c challenge-06
When you are finished (whether or not you solved everything), commit your challenge edits (including unfinished work), then return to the main line before starting Chapter 7:
Uncommitted edits can follow you across branches. Save them before switching; if nothing changed, skip add and commit. The status command should print nothing:
git add -A
git commit -m "Challenge 06: Save practice work"
git status --short
git switch main
Solutions are in the Chapter 6 Answers document. Try each hint in order and only read the next one when you are stuck.
Challenge 1 — Average per die
Goal: show the average value of the dice in the latest roll.
Requirements:
- Add a computed property to
ContentViewthat returns the average ofresultsas aDouble. - Show it under the "Rolling ..." caption in small secondary text, with exactly one decimal place, for example "Average: 4.0".
- Before the first roll, when
resultsis empty, show "Average: 0.0". - Use only concepts from Chapters 1 to 6. (
ifstatements arrive in Chapter 7; you do not need one.)
Acceptance criteria:
- The project builds with no errors or warnings.
- After rolling 4, 2 and 6, the text reads "Average: 4.0". After rolling 5 and 2, it reads "Average: 3.5".
- At launch it reads "Average: 0.0", never "nan", and the app does not crash.
- The average always agrees with the chips on screen.
Hint 1
The average is the total divided by how many dice there are. You already have both numbers: one is a computed property, the other is a property of every array. Think about what happens when there are no dice: what is 0 divided by 0?
Hint 2
Dividing two Ints throws away the fraction, so convert both to Double before dividing (Chapter 2). Dividing a Double by zero does not crash, but produces "not a number", which prints as nan. To avoid that without an if, use the ternary operator from Chapter 5 together with the array's isEmpty property: when the array is empty, the answer is 0; otherwise it is the division.
Hint 3
SwiftUI's Text interpolation accepts a format specifier for numbers: \(someDouble, specifier: "%.1f") shows exactly one digit after the decimal point. Your property's body is one expression of the form results.isEmpty ? 0 : ..., where the false branch divides Double(total) by the Double of the array's count. Put the new Text directly after the caption's .foregroundStyle(.secondary) line, with .font(.footnote) and .foregroundStyle(.secondary).
Challenge 2 — Show the arithmetic
Goal: show how the total was calculated.
Requirements:
- Write a function
breakdown(of values: [Int]) -> StringinContentViewthat returns the values joined by " + ", for example "4 + 2 + 6". - Build the string with a
forloop. - Show the result under the chips in small secondary text.
- With one die, show just its value ("5"). Before the first roll, show nothing.
Acceptance criteria:
- The project builds with no errors or warnings.
- After rolling three dice showing 4, 2 and 6, the text reads exactly "4 + 2 + 6" (no leading or trailing "+").
- After rolling one die showing 5, the text reads "5".
- At launch there is no visible text.
Hint 1
This is the same accumulator pattern as the loop version of sum(of:), but the accumulator is a String that starts empty ("") instead of an Int that starts at 0. You can add text to a String with +=.
Hint 2
The difficulty is the separator: every value except the first needs " + " in front of it. To know whether you are on the first value, loop over the indexes (values.indices) instead of the values, and read each value with values[index]. The first value is the one at index 0.
Hint 3
Inside the loop, use one += whose right-hand side is a ternary: when index == 0, add just the interpolated value; otherwise add " + " followed by the interpolated value. Return the string after the loop. In body, add Text(breakdown(of: results)) after the closing brace of the chips' LazyVGrid. An empty array never enters the loop, so the function returns "", which displays nothing.
Extra Practice
These have no hints. Answers are in the Chapter 6 Answers document.
Exercise A — Predict the output
What does this playground print?
#Playground("Exercise A") {
var values = [3, 5]
values.append(1)
values.append(values[0])
print(values, values.count)
var product = 1
for value in values {
product *= value
}
print(product)
for index in 1..<values.count {
print(index, values[index])
}
}
Exercise B — Spot the bug
This function is meant to print every value with its position, but the app crashes on the last iteration. Find and fix the bug.
func describe(_ values: [Int]) {
for index in 0...values.count {
print("Die \(index + 1): \(values[index])")
}
}
Exercise C — Spot the bug
This sum always returns 0, whatever the array contains. Why?
func sum(of values: [Int]) -> Int {
var total = 0
for value in values {
var total = 0
total += value
}
return total
}
Hint: Xcode shows warnings for this function. What do they tell you?
Exercise D — Small modification
On your challenge branch, write a function countMaximums(in values: [Int], sides: Int) -> Int that returns how many dice rolled the highest possible face (for example, how many 6s in a D6 roll). Use a for loop, an accumulator, and the ternary operator. Show the count under the chips as "Maximums: 2".
Exercise E — Expand a reduce
Rewrite let remaining = [2, 9, 4].reduce(100, -) as a for loop with an accumulator, and predict the result before running either version.