Dice Foundry Solutions and Answer Key

Chapter 6 Answers — Arrays, Loops, and Multiple Dice

Knowledge Check Answers

1. When an array needs a type annotation. Swift infers an array's type from its elements. [GridItem(.flexible()), ...] contains GridItem values, so its type is clearly [GridItem]. An empty literal [] contains nothing to infer from, so Swift cannot know whether it is an array of Int, String or anything else. The annotation : [Int] supplies that information. ([Int]() is an equivalent way to say the same thing.)

2. Valid indexes. For five elements, the first valid index is 0 and the last is 4 (count - 1). Reading index 5 stops the app with "Fatal error: Index out of range". It is a runtime error: the code compiles, because the compiler cannot know how many elements the array will hold while the app runs, and it only fails when that line executes.

3. Closed versus half-open ranges. Use 1...count when counting things, such as "roll dice number 1 through count", where the loop variable is unused or represents a natural count. Use 0..<count when walking indexes, because valid indexes are 0 up to but not including count (or use array.indices, which is the same range). The classic off-by-one bug is for index in 0...array.count { array[index] }: it runs one extra time and crashes on array[array.count]. Another is for _ in 0...count, which repeats count + 1 times.

4. Loop versus reduce. The loop is imperative: you declare an accumulator (var total = 0), update it explicitly for every element (total += value) and return it. You control every step, which makes it easy to trace and extend. values.reduce(0, +) is a collection operation: it expresses the same calculation as "combine all elements with +, starting from 0", and the loop is hidden inside reduce. The first argument, 0, is the initial result and determines the result type; the second, +, is the function that combines the result so far with each element. For an empty array, reduce never calls + and returns the initial value, 0.

5. Computed total and $quantity. total is derived entirely from results. Storing it separately would create two sources of truth that must be kept in sync, and any missed update would show a wrong total. A computed property is recalculated from results every time body reads it, so it is always correct. The Stepper receives $quantity because it must both read and write the value: $quantity is a two-way connection (a binding) to the @State property. Passing quantity would pass only a copy of the current number, which the Stepper could not change. Chapter 10 explains bindings fully.

Challenge Solutions

Challenge 1 — Average per die

File: ContentView.swift · Where: inside struct ContentView, after the total computed property · Action: Add

Example — not part of the Dice Foundry project
    var average: Double {
        results.isEmpty ? 0 : Double(total) / Double(results.count)
    }

File: ContentView.swift · Where: in body, after the caption Text("Rolling \(quantity)\(selectedDie.name)") and its .foregroundStyle(.secondary) line, with a blank line before it · Action: Add

Example — not part of the Dice Foundry project
            Text("Average: \(average, specifier: "%.1f")")
                .font(.footnote)
                .foregroundStyle(.secondary)

Why it works: the average is the total divided by the number of dice. Both are Ints, and Int division would discard the fraction (7 / 2 is 3), so each is converted to Double first. When results is empty, dividing 0.0 by 0.0 would produce "not a number" (nan), so the ternary returns 0 in that case instead. Because average is a Double property, Swift treats the literal 0 as 0.0. The ternary only evaluates the branch it chooses, so the division is never attempted for an empty array. The format specifier "%.1f" in the Text interpolation shows exactly one digit after the decimal point, so 4 appears as "4.0" and 3.6666... as "3.7".

Like total, average is derived from results, so it can never disagree with the chips.

Alternatives: in Chapter 7 you could write the same logic with if results.isEmpty { return 0 }. Instead of the specifier: interpolation you could use average.formatted(.number.precision(.fractionLength(1))), a newer formatting API you may see in other code; it produces a String and respects the user's locale (for example, a decimal comma).

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Folder: challenge-solutions/ch06-average/.

Challenge 2 — Show the arithmetic

File: ContentView.swift · Where: inside struct ContentView, after the closing brace of sum(of:) · Action: Add

Example — not part of the Dice Foundry project
    func breakdown(of values: [Int]) -> String {
        var text = ""
        for index in values.indices {
            text += index == 0 ? "\(values[index])" : " + \(values[index])"
        }
        return text
    }

File: ContentView.swift · Where: in body, after the closing brace of the result chips' LazyVGrid, with a blank line before it · Action: Add

Example — not part of the Dice Foundry project
            Text(breakdown(of: results))
                .font(.footnote)
                .foregroundStyle(.secondary)

Why it works: this is the accumulator pattern with a String. The loop walks indexes rather than values, so it knows which element is first. For index 0 it appends just the number; for every later index it appends " + " and the number. Operator precedence makes the line read as intended: == is evaluated first, then the ternary chooses a string, then += appends it. For [4, 2, 6], text grows from "" to "4", "4 + 2" and "4 + 2 + 6". For one value, only the first branch runs, giving "5". For an empty array, values.indices is the empty range 0..<0, the loop body never runs, and the function returns "", so the Text shows nothing.

Alternatives: Chapter 8 introduces map and joined(separator:), which turn this into one line: values.map { "\($0)" }.joined(separator: " + ") (the $0 shorthand appears in Chapter 14). It is the same relationship as the loop sum and reduce. Another loop-based approach puts the separator after each value and then removes the final " + ", which is harder to get right.

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). Folder: challenge-solutions/ch06-breakdown/.

Extra Practice Answers

Exercise A — Predict the output

[3, 5, 1, 3] 4
45
1 5
2 1
3 3

values.append(values[0]) appends a copy of the first element, 3. The product starts at 1 (the neutral value for multiplication, as 0 is for addition) and becomes 3, 15, 15 and 45. The last loop uses 1..<4, so it skips index 0 and prints indexes 1, 2 and 3 with their values.

Exercise B — Spot the bug

0...values.count includes values.count, which is not a valid index, so the last iteration crashes with "Index out of range". Use the half-open range:

Example — not part of the Dice Foundry project
        for index in 0..<values.count {

or, equivalently, for index in values.indices. Note that index + 1 in the message is fine: it only changes the number printed for humans ("Die 1" instead of "Die 0"), not the index used to read the array.

Exercise C — Spot the bug

The line var total = 0 inside the loop declares a new local variable that shadows the outer total. Each iteration creates a fresh inner total, adds one value to it, and throws it away at the end of the iteration. The outer total is never changed, so the function always returns 0. (A related mistake, total = value instead of total += value, returns only the last value.) Xcode warns that the inner variable is written to but never read, and that the outer one is never mutated; together these point straight at the problem. Fix: delete the inner var total = 0.

Exercise D — Small modification

File: ContentView.swift · Where: inside struct ContentView, with the other functions · Action: Add

Example — not part of the Dice Foundry project
    func countMaximums(in values: [Int], sides: Int) -> Int {
        var count = 0
        for value in values {
            count += value == sides ? 1 : 0
        }
        return count
    }

In body, after the chips' LazyVGrid:

Example — not part of the Dice Foundry project
            Text("Maximums: \(countMaximums(in: results, sides: selectedDie.sides))")
                .font(.footnote)

The ternary adds 1 for each die equal to the number of sides and 0 otherwise. Note one limitation: it uses the currently selected die, so if the player changes the die after rolling, the count refers to the wrong die. Chapter 7 fixes the same problem for the caption by remembering what was rolled. Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target), in a scratch copy of Checkpoint 06.

Exercise E — Expand a reduce

Example — not part of the Dice Foundry project
var remaining = 100
for value in [2, 9, 4] {
    remaining -= value
}

Both versions give 85: ((100 - 2) - 9) - 4. reduce passes the result so far as the left operand and the next element as the right operand, which matters for operators such as - where order changes the answer.