Dice Foundry Solutions and Answer Key

Chapter 3 Answers — SwiftUI Fundamentals

Knowledge Check Answers

1. struct ContentView: View. It declares a new structure type named ContentView: a named type that groups properties and methods. The : View part is protocol conformance. It promises that ContentView meets every requirement of SwiftUI's View protocol, which in practice means it provides a property named body that produces a view. The compiler checks the promise; if body is missing or has the wrong type, the build fails with an error similar to "Type 'ContentView' does not conform to protocol 'View'". In return, SwiftUI can display, preview and modify ContentView like any other view.

2. some View. some View is an opaque type: "one specific type that conforms to View, which the compiler works out from the code." The real type of a body is a long nested type that records every stack and modifier, and it changes whenever you edit the layout. Writing it by hand would be impractical and fragile. some View lets the compiler keep the precise type (which it uses to generate efficient code and to compare old and new descriptions) while you write something short and stable.

3. No redraw instructions. SwiftUI is declarative. body describes what the screen should look like for the current data; it does not contain step-by-step instructions to change the screen. SwiftUI tracks which data each view's body reads. When that data changes, SwiftUI reads body again to get a new description, compares it with the previous description, and updates only the parts of the real screen that differ. This is the same desired-state model as a Terraform plan or a Kubernetes controller: you declare the target, and the framework reconciles. In this chapter there is no changing data at all, so body is read when the screen appears and again only for system changes such as Dark Mode.

4. ZStack order. The last child is in front. A ZStack draws its first child at the back and each later child on top of the ones before it. The circle is a backdrop for the number, so it must be drawn first (at the back) and the number second (in front). If the order were reversed, the semi-transparent circle would be drawn over the number.

5. Padding and background order. Each modifier wraps the view produced by everything above it. In Text("Dice").padding().background(Color.orange), the padding is added first, so the background wraps the text plus its padding and you see a roomy orange box. In Text("Dice").background(Color.orange).padding(), the background wraps only the text, so it hugs the letters, and the padding is then added outside the orange as transparent space.

Challenge Solutions

Challenge 1 — Add a roll-settings strip

File: ContentView.swift · Where: inside VStack(spacing: 24) { ... }, directly after the caption's .foregroundStyle(.secondary) line and before the second Spacer() · Action: Add

Example — not part of the Dice Foundry project
            HStack(spacing: 12) {
                Text("D6")
                    .font(.headline)
                    .padding(8)
                    .background(Color.orange.opacity(0.2))
                Text("1 die")
                    .font(.headline)
                    .padding(8)
                    .background(Color.orange.opacity(0.2))
                Text("Modifier +0")
                    .font(.headline)
                    .padding(8)
                    .background(Color.orange.opacity(0.2))
            }

Leave a blank line before the HStack to match the rest of the file's spacing between sections.

Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The verified project is in challenge-solutions/ch03-status-strip/.

Why it works:

  • The HStack places the three labels side by side, and spacing: 12 sets the gap between them once, on the container.
  • Because the HStack is a single child of the main VStack, it is placed between the caption and the second spacer, 24 points below the caption (the VStack's spacing).
  • Each label's modifiers run from the inside out: .font(.headline) sets the text style, .padding(8) adds 8 points of space on every side, and .background(...) then wraps the already-padded view, so the orange covers the padding as well as the letters.
  • Nothing else in the layout changes. The two spacers simply have a little less room to share.

Common mistakes:

  • .background(...) before .padding(8): the orange hugs the letters and the padding is transparent. This fails the acceptance criterion about the padding being inside the orange.
  • Putting the strip after the second Spacer(): the strip then sits just above the button instead of under the caption.
  • Putting .font(.headline) on the HStack instead of on each label: this actually works, because the font setting flows down to the texts inside the stack. It is a valid alternative (see below).

Alternatives:

  • Move .font(.headline) from the three labels to the HStack itself. The font flows down to every Text in the stack, which removes two repeated lines. The padding and background must stay on each label, because they should produce three separate orange boxes, not one large box around the whole row.
  • You may notice that the three labels repeat the same three modifiers. In Chapter 10 you learn to extract repeated views into reusable components, and in Chapter 11 you learn to write your own modifier (cardStyle()). For a static three-label strip, the repetition is acceptable and easy to read.

Challenge 2 — Draw the tree

One correct answer:

ContentView                                     (container: its body returns one view)
  VStack (spacing 24, padded)                   container
    HStack                                      container
      Image "dice.fill"                         leaf
      Text "Dice Foundry"                       leaf
    Spacer                                      leaf
    ZStack                                      container
      Circle (160 x 160)                        leaf
      Text "6"                                  leaf
    Text "Tap Roll Dice to begin"               leaf
    HStack (spacing 12)                         container
      Text "D6"                                 leaf
      Text "1 die"                              leaf
      Text "Modifier +0"                        leaf
    Spacer                                      leaf
    Button "Roll Dice"                          leaf (see note)

Why it is correct: each line that starts a view in the code appears once, and its depth matches its indentation in the Swift file. Modifiers are not nodes; they adjust the node they are attached to.

Note on the button: from the point of view of your layout code, the button is a leaf, because you gave it a string title rather than child views. Internally, SwiftUI builds a text label for it. In Chapter 5 you write a button with an explicit label: closure, and then it clearly contains child views. Either classification is acceptable here if you can explain it.

Extra Practice Answers

Exercise 1 — Predict the layout

The Spacer() at the top of the VStack pushes the HStack to the bottom of the screen. Inside the HStack, the Spacer() between the two texts pushes "D4" to the leading (left) edge and "D20" to the trailing (right) edge. With .padding() on the whole stack, both texts sit about 16 points in from the screen edges. Result: "D4" in the bottom-left corner and "D20" in the bottom-right corner, with nothing else on screen.

Exercise 2 — Spot the bug

The four modifier lines are inside the action closure, after print("Roll Dice tapped"). Swift reads a line that starts with a dot as continuing the expression on the line before it, so it tries to apply .font(.title2) to the result of print(...). print returns an empty value written (), which is not a view and has no font member. The compiler reports an error similar to:

Value of tuple type '()' has no member 'font'

Fix: move the four modifier lines below the closing } of the action closure, indented to the same level as the word Button, so they modify the button rather than the print call. This is exactly the layout in Step 7 of the chapter.

Exercise 3 — Spot the bug

The .frame(width: 160, height: 160) is attached to the Text, not the Circle. The text gets a 160-point frame (which you cannot see, because the text has no background). The circle has no frame, and a shape with no frame expands to fill the space it is offered, so it grows to the full width of the screen. Fix: move the .frame(...) line so it follows the circle's .fill(...) line.

Exercise 4 — Small modification

Inside the title HStack, move the Text("Dice Foundry") line and its two modifier lines above the Image(systemName: "dice.fill") line. HStack arranges children in code order, so the text now comes first (left) and the icon second (right). Then change the icon's .font(.title) line to .font(.largeTitle). SF Symbols size themselves from the font, so the icon grows to match the title's text style. The result:

Example — not part of the Dice Foundry project
            HStack {
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                Image(systemName: "dice.fill")
                    .font(.largeTitle)
                    .foregroundStyle(.orange)
            }

Exercise 5 — Predict the colors

"Dice" is in the secondary (muted gray) style and "Foundry" is orange. .foregroundStyle(.secondary) on the VStack flows down to every view inside it that has not set its own style. "Foundry" sets its own style, .orange, which is closer to the text and wins. In SwiftUI, a setting applied closer to a view overrides the same setting inherited from a container.