Chapter 3 — SwiftUI Fundamentals
In Chapter 2 you learned the basic vocabulary of Swift: constants, variables, types, operators and optionals. None of that changed what the app looks like. In this chapter you put Swift to work on the screen. You learn what a SwiftUI view is, why ContentView is written as a struct that "conforms to" a protocol called View, what the mysterious some View means, and how a handful of building blocks (text, images, buttons, stacks, spacers and shapes) combine into a real layout. By the end, Dice Foundry has a proper face: a title with a dice icon, a large die display in the middle of the screen, a short caption, and an orange Roll Dice button at the bottom. The button does not roll anything yet; it prints a message to Xcode's debug console so you can prove it works. Making it roll is Chapter 4's job.
This chapter matters beyond Dice Foundry. Every SwiftUI screen you will ever read, whether you wrote it, a colleague wrote it, or an AI assistant generated it, is built from exactly the ideas in this chapter. Once you can read a body as a tree of views with modifiers attached, most SwiftUI code stops looking like magic.
Learning Objectives
By the end of this chapter you will be able to:
- Explain what a SwiftUI view is and why views are lightweight descriptions rather than objects on the screen.
- Read a
structdeclaration and explain what a structure is used for. - Explain protocol conformance, and what the
Viewprotocol requires ofContentView. - Explain the role of the
bodyproperty and whatsome Viewmeans. - Describe the difference between declarative and imperative user interface code, and explain why SwiftUI does not generally require you to redraw the interface manually.
- Draw the view hierarchy of a SwiftUI screen as a tree.
- Use
Text,Image,Button,VStack,HStack,ZStack,SpacerandCircle. - Apply view modifiers for padding, frames, colors and fonts, and explain why the order of modifiers matters.
- Recognize trailing closure syntax and explain why
Button("Roll Dice") { ... }andVStack { ... }are written that way. - Find SF Symbol names in the SF Symbols app and use them with
Image(systemName:). - Use the preview canvas to check a layout, and use
printwith the debug console to confirm that a button's action runs.
Concept Explanation
What a view is
On an iPhone, everything you see is drawn by the system: letters, icons, buttons, background colors. In SwiftUI you never draw those pixels yourself. Instead you write views: small Swift values that describe a piece of interface. Text("Dice Foundry") is a view that says "there should be some text here, and it reads Dice Foundry." Image(systemName: "dice.fill") is a view that says "there should be the system's filled-dice icon here."
A view is a description, not the thing on screen. SwiftUI reads your descriptions and takes care of creating, positioning, drawing and updating the real on-screen elements. That division of labor is the core idea of the whole framework:
- You describe what the screen should contain for the current data.
- SwiftUI works out how to make the screen look like that, and keeps it that way.
Because views are only descriptions, they are cheap. SwiftUI creates and throws them away constantly, often many times per second while something animates. You should never think of a SwiftUI view as "the button object that lives on the screen." Think of it as "the current recipe for the button."
Structures: the struct keyword
Open ContentView.swift and look at the line that starts the main declaration:
struct ContentView: View {
The keyword struct declares a structure: a named type that groups related values and behavior together. In Chapter 2 you used types that Swift provides, such as Int and String. A struct lets you create your own type. Everything between the opening brace { and its matching closing brace } belongs to that type.
A structure can contain:
- Properties: named values stored in or computed by the structure (you met
letandvarin Chapter 2; inside a structure they become properties). - Methods: functions that belong to the structure (you write your first one in Chapter 4).
ContentView currently has exactly one property, body, and no methods. In later chapters you add more properties (for example the current die result) and methods (for example a function that rolls a die).
Swift has another way to declare your own types, class. SwiftUI views are almost always structures, and you will see why in Chapter 13 when we compare the two. For now, the important fact is simple: a SwiftUI view is a struct. If an AI assistant ever hands you class ContentView: View, something has gone wrong.
By convention, Swift type names use UpperCamelCase (ContentView, DiceFoundryApp, String), and property, variable and function names use lowerCamelCase (body, result, rollDie). The compiler does not enforce this, but every Swift developer follows it, so the capitalization tells you at a glance whether a name refers to a type or to a value.
Protocols and protocol conformance
The : View after struct ContentView is called protocol conformance. A protocol is a named list of requirements: properties and methods a type must provide. When a type writes : SomeProtocol after its name, it promises to meet every requirement in that list. The compiler checks the promise. If the type does not provide something the protocol requires, the project does not build.
View is a protocol defined by SwiftUI. Its main requirement is one property:
- a property named
bodythat produces some other view.
That is all ContentView needs to become something SwiftUI can display. In return for meeting the requirement, ContentView gets everything SwiftUI provides to views: it can be placed inside other views, previewed in the canvas, and decorated with modifiers such as .padding().
Think of a storage driver API in an operating system, or a provider interface in Terraform. The kernel does not care which vendor wrote the driver, as long as the driver implements the required entry points (open, read, write, close). A protocol is the same kind of contract. SwiftUI does not care what your view is called or what it shows, as long as it implements body. Conforming to View is like registering a driver that implements the expected interface: once it does, the system knows how to use it.
You have actually seen a second protocol already. In DiceFoundryApp.swift, the line struct DiceFoundryApp: App { declares a structure that conforms to the App protocol, whose requirement is a body that produces a scene. Same pattern, different contract.
If you break the contract, the compiler tells you immediately. Rename body to bdy, and the build fails with an error similar to:
Type 'ContentView' does not conform to protocol 'View'
Xcode often offers a Fix button that adds a stub for the missing requirement. The fix is rarely what you want (you meant body, not a second property), but the message points you at exactly the right place: the type no longer keeps its promise.
The body property
Here is the line that begins the body property:
var body: some View {
Read it as: "ContentView has a property named body, whose type is some kind of view, and here is the code that produces it."
Unlike the variables you wrote in Chapter 2, body does not store a value. The braces after some View contain code that computes the value every time someone asks for it. This is called a computed property. You learn to write your own computed properties in Chapter 5; for now it is enough to know that whenever SwiftUI needs to know what ContentView looks like, it reads body, the code in the braces runs, and the result is a fresh description of the screen.
Two consequences follow, and both matter for the rest of the course:
- SwiftUI decides when
bodyruns, not you. You never writecontentView.bodyyourself. SwiftUI reads it when the view first appears and again whenever something the view depends on changes. bodyshould only describe the interface. It may run many times. It should not do slow work, change data, or print messages as a side effect. Work that should happen once, in response to a tap, belongs in the button's action, as you will see later in this chapter.
some View: an opaque return type
Why some View and not just View?
Every view in SwiftUI has a precise type. Text("Dice Foundry") is a Text. Add .padding() and it becomes a different type that wraps the Text. Put that inside a VStack with a Button and a Spacer, and the precise type of the whole thing becomes a long, nested type name that describes every layer. For the layout you build in this chapter, the exact type would run to several lines of angle brackets. Nobody wants to write that, and it would change every time you edited the layout.
some View means: "this property returns one specific type that conforms to View. The compiler knows exactly which type; I am not going to spell it out." This is called an opaque type. The compiler works out the real type from the code in the braces, uses it to generate efficient code, and lets you keep writing some View.
There are two practical rules to remember:
bodymust return one value. In this chapter that single value is aVStack, which in turn contains everything else.- Writing just
View(withoutsome) is not the same thing. If you tryvar body: View {, Swift reports thatContentViewno longer conforms toView, and you also get a warning similar to "use of protocol 'View' as a type must be written 'any View'." The fix is to putsomeback.
Many professional Swift developers use some View every day without thinking about type theory. What you need: some View means "a view, of a type the compiler figures out." That is enough to read and write every view in this course.
Declarative versus imperative user interface code
Older iPhone frameworks (UIKit) are imperative: you create a label object, add it to the screen, and later, when data changes, you write instructions to change it: "set this label's text to 4", "hide that button", "move this image 20 points down." Your code is a sequence of commands that mutate the screen step by step. Every time data changes, you must remember every piece of the screen that depends on it and update each one.
SwiftUI is declarative: you write a description of what the screen should look like for the current data, and the framework makes the screen match. You do not write "change the label to 4." You write "the label shows the current result," and when the result changes, SwiftUI re-reads your description and updates whatever differs.
You have probably worked with declarative infrastructure: a Terraform configuration, a Kubernetes manifest, an Ansible playbook written to be idempotent. You declare the desired state ("three replicas, this image, this port"), and a controller compares desired state with actual state and makes whatever changes are needed. You do not write "start one more container." SwiftUI's body is the manifest, and SwiftUI is the controller. When your data changes, SwiftUI re-evaluates the manifest, compares the new description with the previous one, and applies only the differences to the screen.
Why you do not redraw the interface yourself
People coming from other environments often ask: "Where do I call refresh?" or "How do I tell the screen to redraw?" In SwiftUI you generally do not. Here is why, in four steps:
- Your
bodyis a description of the screen as a function of data. - SwiftUI tracks which data each view's
bodyreads. - When that data changes, SwiftUI marks the view as out of date and reads its
bodyagain, producing a new description. - SwiftUI compares the new description with the old one and updates only the parts of the real screen that changed.
your data changes
|
v
SwiftUI notices (it tracks what body reads)
|
v
SwiftUI asks for body again ---> new description of the screen
|
v
SwiftUI compares old and new descriptions
|
v
only the differences are applied to the real screen
In this chapter nothing ever changes: the die always shows "6". SwiftUI reads body, draws the screen, and has no reason to read it again (except for system events such as rotating the device or switching to Dark Mode). In Chapter 4 you add the first piece of changing data, called state, and you will watch this loop run every time you tap the button. The important point now is that you will not write a single line of "redraw" code, in Chapter 4 or anywhere else in the course.
There are rare cases where SwiftUI cannot see a change (for example data held in some kinds of objects that SwiftUI is not told about). Chapter 13 discusses how SwiftUI observes data stored in a class. In ordinary SwiftUI code built the way this course teaches, you never trigger redraws manually.
View hierarchies
A screen in SwiftUI is a tree of views. Container views, such as stacks, hold child views; those children can be containers themselves. The view at the top of the tree for our screen is ContentView, and its body returns a vertical stack that contains everything else.
Here is the hierarchy you build in this chapter:
ContentView
VStack (spacing 24, then padded)
|-- HStack title row
| |-- Image "dice.fill"
| |-- Text "Dice Foundry"
|-- Spacer flexible gap
|-- ZStack die display
| |-- Circle (160 x 160) back layer
| |-- Text "6" front layer
|-- Text "Tap Roll Dice to begin" caption
|-- Spacer flexible gap
|-- Button "Roll Dice"
Reading code as a tree is one of the most useful skills in SwiftUI. The indentation in your Swift file mirrors this tree: every time you go one level deeper in the tree, the code is indented four more spaces. When a layout looks wrong, the first question is almost always "which container is this view really inside?", and the indentation answers it.
The tree also extends upward. In Chapter 1 you saw that DiceFoundryApp creates a WindowGroup containing ContentView(). So the full chain is: the app, its scene (WindowGroup), ContentView, and then the tree above.
The building blocks
Text
Text displays read-only text. You give it a string literal: Text("Dice Foundry"). It wraps onto several lines if there is not enough horizontal room, and by default uses the system font at the standard body size.
Image and SF Symbols
Image displays a picture. With the systemName: label, it displays one of Apple's SF Symbols: thousands of icons designed to match the system font, scale with text, and take on colors. Image(systemName: "dice.fill") displays a pair of filled dice.
The name must match a symbol exactly. Apple's free SF Symbols app (download it from Apple's developer website, under Fonts / SF Symbols) lets you browse and search every symbol, see which iOS version introduced it, and copy its exact name. Search for "dice" and you will find dice (outlined, used by the Chapter 1 template edit) and dice.fill (filled). Names are case-sensitive and use dots between words.
If you mistype the name, the project still builds, because the name is just a string. At run time the image is simply empty, and Xcode prints a message to the debug console similar to "No symbol named 'dice.fil' found in system symbol set." An icon that silently vanishes is almost always a misspelled symbol name.
Button
Button is a view the user can tap. It has two parts: a label (what the button shows) and an action (code to run when it is tapped). The simplest form takes the label as a string and the action as a block of code in braces:
Button("Roll Dice") {
print("Roll Dice tapped")
}
The block of code in braces is not run when the screen is drawn. SwiftUI keeps it and runs it later, each time the user taps the button. The way it is written (the braces after the parentheses) is called trailing closure syntax, which is explained below.
Stacks: VStack, HStack and ZStack
Stacks are the main layout containers:
| Stack | Arranges its children | Typical use |
|---|---|---|
VStack |
top to bottom (vertically) | a screen's main column |
HStack |
leading to trailing (horizontally; left to right in English) | an icon next to a label |
ZStack |
back to front (layered on top of one another) | text on top of a shape |
The "Z" in ZStack comes from the z-axis: the imaginary axis pointing out of the screen toward you. In a ZStack, the first child is at the back and each later child is drawn on top of the previous ones. That is why our Circle comes first and the number second: the number must sit on top of the circle.
Stacks accept an optional spacing: argument that sets the gap between children. VStack(spacing: 24) puts 24 points between each pair of children. Without it, SwiftUI picks a default spacing that suits the platform.
Sizes in SwiftUI are measured in points. An iPhone screen has two or three physical pixels per point, depending on the model, and the system handles the conversion. A 160-point circle looks the same physical size on every modern iPhone.
Stacks also align their children. By default VStack centers its children horizontally, and HStack centers them vertically. You can change this with an alignment: argument (for example VStack(alignment: .leading)), which you will see in later chapters.
Spacer
Spacer() is an invisible, flexible view that expands to take up as much space as it can along the stack's direction. In a VStack, a Spacer pushes the views before it up and the views after it down. When there are two spacers, they share the leftover space equally.
Our layout uses two spacers: one between the title and the die display, and one between the caption and the button. The result is a title pinned to the top, a button pinned to the bottom, and the die display floating in the middle. On a taller or shorter iPhone, the spacers grow or shrink and the layout adapts without any extra code.
Circle: your first shape
Circle() is a shape. Shapes are views that draw geometry. A shape has no natural size: it expands to fill whatever space it is offered. That is why we give our circle an explicit size with .frame(width: 160, height: 160). Without the frame, the circle would try to fill all the space the stack can give it. Shapes are filled with the foreground color by default; .fill(...) chooses a specific color. (Chapter 11 introduces other shapes, such as rounded rectangles, along with outlines and gradients.)
View modifiers
A modifier is a method you call on a view to produce a new, adjusted view. You write it on the line after the view, starting with a dot:
Text("Dice Foundry")
.font(.largeTitle)
.fontWeight(.bold)
Read this from top to bottom: "a text that says Dice Foundry, with the large-title font applied, with bold weight applied." Each modifier takes the view above it and wraps it in a new view that adds one adjustment. The original Text is not changed; it is wrapped.
Modifiers you use in this chapter:
| Modifier | What it does |
|---|---|
.font(...) |
Sets the font for text inside the view. |
.fontWeight(.bold) |
Sets the font weight. |
.foregroundStyle(...) |
Sets the color (or style) used for text and symbols. |
.fill(...) |
Fills a shape with a color. |
.frame(width:height:) |
Proposes a fixed size for the view. |
.padding() |
Adds space around the view (the system's standard amount, about 16 points). |
.buttonStyle(...) |
Chooses the overall look of a button. |
.controlSize(...) |
Chooses the size of controls such as buttons. |
.tint(...) |
Sets the accent color for controls. |
Some modifiers apply to one view; others pass their setting down the tree. .font(.title2) on a Button sets the font of the button's label. If you put .font(.title2) on a VStack, every text inside the stack that has not set its own font would use it. This "flowing down" behavior comes from SwiftUI's environment, which you will use deliberately in Chapter 11.
Leading-dot values
Many modifier arguments start with a dot: .title, .orange, .bold, .secondary, .borderedProminent, .large. Each is a named preset of the type the modifier expects. .font(...) expects a Font, so .title means Font.title. .tint(...) expects a color, so .orange means the system orange color. Swift lets you leave out the type name because it already knows which type is expected. You will learn how to define your own named cases with enum in Chapter 5.
Fonts
SwiftUI fonts come in two flavors:
- Text styles such as
.largeTitle,.title,.title2,.headline,.bodyand.caption. These describe the role of the text, and they automatically grow or shrink with the user's preferred text size (Dynamic Type, set in the Settings app). Prefer them for ordinary text. - Explicit sizes, written
.system(size: 72, weight: .bold). This gives you exact control. We use it for the big die number because no text style is large enough. The trade-off is that an explicit size does not follow the user's text-size setting. Chapter 11 shows how to make even this number scale (@ScaledMetric).
Colors
SwiftUI's Color type provides system colors such as .orange, .red and .blue. System colors adapt slightly between Light and Dark Mode so they stay readable. A color can be made partially transparent with .opacity(...), which takes a value from 0 (invisible) to 1 (fully opaque). Color.orange.opacity(0.2) is a pale, see-through orange, which is why the circle looks like a soft disc behind the number.
There are also semantic styles such as .secondary, which means "the style for less important content." On a light background it renders as a muted gray; in Dark Mode it adapts automatically. Using .secondary for the caption tells SwiftUI the caption's role, and SwiftUI picks the right color for the situation. In Chapter 11 you add your own named colors to the asset catalog.
Modifier order matters
Because each modifier wraps the view above it, the order you write modifiers in changes the result. This is one of the most common surprises in SwiftUI. Compare these two snippets (they are demonstrations, not part of the project):
Text("Dice Foundry")
.padding()
.background(Color.orange)
Text("Dice Foundry")
.background(Color.orange)
.padding()
In the first snippet, the text is padded first, making a larger view (text plus 16 points of space on each side), and then that larger view gets an orange background. You see a generous orange box with the text in the middle.
In the second snippet, the text gets an orange background first, which hugs the letters tightly, and then that view is padded. The padding adds empty, transparent space around an already-colored box. You see a tight orange strip behind the letters, with clear space around it.
Illustrative mockup — not a screenshot
First snippet (padding, then background):
+----------------------------+
| | <- orange fills the
| Dice Foundry | padded area too
| |
+----------------------------+
Second snippet (background, then padding):
+--------------+
| Dice Foundry | <- orange hugs the text;
+--------------+ padding is transparent
The same logic applies to .frame and .background: a background applied before a frame covers only the view's natural size; a background applied after the frame covers the whole frame.
Imagine the snippet Text("6").frame(width: 160, height: 160).background(Color.orange) and a second snippet with the same three parts, except .background(Color.orange) comes before .frame(width: 160, height: 160). In each case, how big is the orange area: the size of the character "6", or a 160 by 160 square? Decide before you read the answer in Prediction Answers.
The .background(...) modifier is used here only to make the order visible. You will use backgrounds in the real project in Chapter 11.
The view at the top is the innermost layer. Each modifier below it adds a layer around everything above it. When a layout looks wrong, read the chain from the top down and ask, for each modifier, "what exactly is this wrapping?"
Trailing closure syntax
Look again at the button:
Button("Roll Dice") {
print("Roll Dice tapped")
}
Button takes two arguments: the title and the action. The action is a closure: a block of code that can be stored and run later. Chapter 4 explains closures in detail. Here we focus on how the code is written.
The long form passes both arguments inside the parentheses, with a label for the action:
Button("Roll Dice", action: {
print("Roll Dice tapped")
})
This works, but the closing }) is awkward, especially when the closure is long. Swift offers trailing closure syntax: when the last argument of a call is a closure, you may write it after the closing parenthesis, and leave out its label. That gives the form you typed:
Button("Roll Dice") {
print("Roll Dice tapped")
}
Both forms mean exactly the same thing to the compiler. SwiftUI code uses trailing closures everywhere, and you have been reading them since Chapter 1 without being told:
VStack { ... }passes the stack's content (its child views) as a trailing closure.VStack(spacing: 24) { ... }passesspacingin the parentheses and the content as a trailing closure.WindowGroup { ContentView() }inDiceFoundryApp.swiftpasses the window's content as a trailing closure.#Preview { ContentView() }passes the preview's content as a trailing closure.
When a call has only a trailing closure and no other arguments, the empty parentheses can be dropped too, which is why you see VStack { and HStack { rather than VStack() {.
The closures passed to stacks are special in one way: inside them, you simply list views one after another, with no commas, and SwiftUI collects them into the stack. This feature is called a view builder. It is why the body of a stack reads like a list of views rather than like ordinary code.
Printing to the debug console
print(...) writes text to the debug console: the lower-right area of Xcode's debug area, which appears while your app runs. It is the simplest way to answer the question "did this code actually run?"
Using print to confirm that a code path ran is the same habit as dropping an echo "reached step 3" into a shell script or tailing a log while you trigger an action. It is not a substitute for a debugger (Chapter 12 introduces breakpoints), but it is fast, and it is often all you need.
The user of your app never sees print output. It exists only for you, the developer, when the app is run from Xcode. To see it:
- Run the app with ⌘R.
- Show the debug area with ⇧⌘Y if it is hidden.
- If the debug area shows two panes, the console is the right-hand pane. The buttons in the debug area's bottom-right corner show or hide each pane.
The preview canvas runs your view in a special preview process. Depending on your Xcode version, print output from a preview may not appear in the debug console at all, or may appear somewhere less obvious. When you need to see console output, run the app in the Simulator with ⌘R.
The preview canvas
The #Preview block at the bottom of ContentView.swift (introduced in Chapter 1) tells Xcode how to show this view in the canvas, the panel to the right of the editor. Show or hide the canvas with ⌥⌘↩ (Editor → Canvas).
Useful canvas habits:
- Leave the canvas open while you edit layouts. It updates as you type, usually within a second or two. You can see the effect of a modifier without building and running the whole app.
- Resume the preview with ⌥⌘P if it pauses. Previews pause when you make a change that needs a full rebuild, or after a build error.
- Live mode versus Selectable mode. At the bottom of the canvas are mode buttons. In the default Live mode, the preview is interactive: you can tap buttons. In Selectable mode, clicking a view in the canvas selects the matching code in the editor, which is a great way to answer "which line produces this thing on screen?" The exact controls vary slightly between Xcode versions.
- Device choice. A menu at the bottom of the canvas lets you pick the preview device. Try a small and a large iPhone to see how the spacers adapt.
The canvas is for fast visual feedback. The Simulator (⌘R) runs the real app, with the real app entry point, and is where you confirm behavior. Use both.
AI assistants produce a lot of SwiftUI layout code, and it usually compiles. The problems are subtler: deeply nested stacks that could be one stack with spacing:, modifiers in an order that silently does nothing (a .background applied before the .padding it was meant to fill), hard-coded .frame sizes on everything, or .font(.system(size: 17)) where a text style such as .body would respect the user's text size. When you review generated layout code, sketch the view tree as in this chapter, then read each modifier chain from top to bottom and ask what it wraps. When you direct an assistant, be specific in the same vocabulary: "Put the icon and title in an HStack; use a VStack with spacing 24; use text styles, not fixed sizes, except for the die number." Precise vocabulary gets precise code.
Syntax Breakdown
This section goes through the new syntax in this chapter token by token. Syntax from Chapter 2 (string literals, let, var, numbers) is not repeated.
struct ContentView: View {
| Token | Meaning |
|---|---|
struct |
Keyword: declares a new structure type. |
ContentView |
The name of the new type (UpperCamelCase because it is a type). |
: |
Here it introduces the protocols this type conforms to. (In let x: Int, the colon introduces a type annotation; same symbol, related meaning: "is a kind of".) |
View |
The SwiftUI protocol ContentView promises to conform to. |
{ |
Opens the body of the structure. Everything up to the matching } belongs to ContentView. |
Together: "Declare a structure named ContentView that conforms to SwiftUI's View protocol."
var body: some View {
| Token | Meaning |
|---|---|
var |
Declares a property. A computed property must use var, even though you never assign to it. |
body |
The property name required by the View protocol. It must be spelled exactly this way. |
: |
Introduces the property's type. |
some |
Marks an opaque type: one specific type the compiler determines from the code. |
View |
The protocol that the specific type conforms to. |
{ |
Opens the code that computes the property each time it is read. |
Together: "body is a property whose value is computed by the code in these braces, and whose type is a specific view type the compiler works out."
VStack(spacing: 24) {
| Token | Meaning |
|---|---|
VStack |
The vertical stack type. Writing a type name followed by parentheses creates a new value of that type. |
( ) |
Wrap the arguments passed when creating it. |
spacing: |
An argument label: names which value you are passing. Chapter 4 explains labels in detail. |
24 |
The spacing value in points. |
{ ... } |
The trailing closure holding the stack's child views (a view builder: one view per line, no commas). |
Image(systemName: "dice.fill")
| Token | Meaning |
|---|---|
Image |
The image view type. |
systemName: |
Argument label meaning "the name of an SF Symbol" (as opposed to an image in your asset catalog). |
"dice.fill" |
The symbol's exact name, as a string. Typos are not caught by the compiler. |
.font(.title) and .foregroundStyle(.orange)
| Token | Meaning |
|---|---|
. (first) |
Calls a modifier on the view written just above. The dot must start the line after the view (or directly follow it). |
font / foregroundStyle |
The modifier's name. |
( ) |
The modifier's argument. |
.title / .orange |
A leading-dot value: a named preset of the expected type (Font.title, the system orange). |
.fontWeight(.bold)
Sets the weight of the text. .bold is a named preset of the font-weight type. Other weights include .regular, .semibold and .heavy.
Circle() and .fill(Color.orange.opacity(0.2))
| Token | Meaning |
|---|---|
Circle |
A shape type. |
() |
Creates a circle. It needs no arguments. |
.fill( |
A modifier for shapes: fill the shape's interior with the given color. |
Color |
SwiftUI's color type, written out in full here. |
.orange |
The system orange color (Color.orange). |
.opacity(0.2) |
A method on the color: returns a new color with 20 percent opacity. |
) |
Closes .fill. |
Here Color.orange is written in full rather than as .orange because we call .opacity on it. Inside .fill(...), writing .orange.opacity(0.2) would also compile, but writing Color makes it obvious that we are building a color value step by step.
.frame(width: 160, height: 160)
| Token | Meaning |
|---|---|
.frame( |
Modifier that gives the view a specific size. |
width: 160 |
Labeled argument: 160 points wide. |
, |
Separates arguments. |
height: 160 |
Labeled argument: 160 points tall. |
.font(.system(size: 72, weight: .bold))
| Token | Meaning |
|---|---|
.font( |
The font modifier you already know. |
.system( |
A leading-dot value that takes arguments: build a system font with specific settings. |
size: 72 |
72-point text. |
weight: .bold |
Bold weight. |
)) |
The first closes .system(...), the second closes .font(...). |
Matching parentheses from the inside out is a skill worth practicing. Xcode helps: put the cursor just after a closing parenthesis and Xcode briefly highlights its partner.
Spacer()
Creates a flexible empty view. No arguments are needed.
Button("Roll Dice") { print("Roll Dice tapped") }
| Token | Meaning |
|---|---|
Button |
The button type. |
("Roll Dice") |
The title shown on the button. |
{ |
Opens the trailing closure: the action. |
print( ... ) |
Writes its argument to the debug console. |
"Roll Dice tapped" |
The message to write. |
} |
Closes the action closure. |
Together: "Create a button titled Roll Dice; when it is tapped, print Roll Dice tapped to the console."
.buttonStyle(.borderedProminent), .controlSize(.large), .tint(.orange)
| Modifier | Meaning |
|---|---|
.buttonStyle(.borderedProminent) |
Use the system's most prominent button style: a filled shape behind the title. Ideal for a screen's main action. Other styles include .bordered (a lighter fill) and .borderless. |
.controlSize(.large) |
Make the control larger (more padding around the title, bigger touch target). Other sizes include .small and .regular. |
.tint(.orange) |
Use orange as the button's accent color, which becomes the fill color for this style. |
.padding()
| Token | Meaning |
|---|---|
.padding |
Adds space around the view. |
() |
With no arguments: the system's standard amount on all four edges. You can also write .padding(8) for 8 points, or specify edges, which you will see later. |
Guided Implementation
In this section you rebuild ContentView.swift into the static Dice Foundry interface, one small step at a time. After each step, glance at the canvas to see the change.
Before you begin:
- Open your Dice Foundry project from Chapter 2.
- Open
ContentView.swiftin the Project navigator (⌘0 shows the navigator if it is hidden). - Show the canvas with ⌥⌘↩ and make sure the preview is running (press ⌥⌘P if it says it is paused).
In Chapter 2 you created SwiftPractice.swift with #Playground blocks. It does not affect the app, so you may keep it as a scratchpad or delete it (select it in the Project navigator, press Delete, and choose Move to Trash). The reference checkpoints from this chapter onward do not include it, so if you compare your project with a reference folder, that file will be the one difference you can ignore.
Your starting ContentView.swift should contain this structure (the comment header at the top of the file is not shown):
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "dice")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Dice Foundry")
}
.padding()
}
}
#Preview {
ContentView()
}
If yours differs, compare it with Reference-Checkpoints/Checkpoint-02-Swift-Fundamentals/DiceFoundry/ContentView.swift and fix it before continuing.
Step 1 — Give the main stack a fixed spacing
File: ContentView.swift · Where: the first line inside body, which currently reads VStack { · Action: Replace
Before:
VStack {
After:
VStack(spacing: 24) {
What it does: sets the gap between every pair of children in the main column to 24 points.
Why it is written this way: the default spacing is fine for two small views, but the finished screen has a title, a die display, a caption and a button. A deliberate, slightly generous spacing makes the layout feel calm and consistent. Putting the value on the stack, rather than adding padding to each child, keeps the spacing in one place, so changing it later is a one-line edit.
What should happen: the canvas updates and the icon and title move a little further apart. Nothing else changes.
Step 2 — Build the title row
The template's icon sits above the title. We want the icon beside the title, so they need their own horizontal stack.
File: ContentView.swift · Where: inside VStack(spacing: 24) { ... }, the four lines from Image(systemName: "dice") through Text("Dice Foundry") · Action: Replace
Before:
Image(systemName: "dice")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Dice Foundry")
After:
HStack {
Image(systemName: "dice.fill")
.font(.title)
.foregroundStyle(.orange)
Text("Dice Foundry")
.font(.largeTitle)
.fontWeight(.bold)
}
What it does: creates a horizontal row containing a filled-dice icon followed by the app name. The icon is sized with the title font and colored orange. The app name uses the large-title text style in bold.
Why it is written this way:
- An
HStackis the natural container for "this, then that, side by side." dice.fillis a more solid icon than the template's outlineddice, which looks better in color. (Open the SF Symbols app and search for "dice" to see both.)- SF Symbols behave like text:
.font(.title)sets the icon's size so it matches nearby text. That is why we use.fontrather than.imageScalehere. .foregroundStyle(.orange)colors only the icon, because the modifier is attached to theImage, not to the stack. If you moved it to theHStack, both the icon and the title would turn orange. Try it, look at the canvas, then put it back.- The title uses
.largeTitle, the biggest standard text style, because it is the screen's heading, and.fontWeight(.bold)to give it weight.
Notice the indentation: the Image and Text are indented one level deeper than HStack, and their modifiers one level deeper still. If your indentation looks off after pasting or typing, select the code and press ⌃I to let Xcode re-indent it.
What should happen: the canvas shows an orange dice icon to the left of a large, bold "Dice Foundry" title, both in the vertical center of the screen.
Step 3 — Add the first spacer
File: ContentView.swift · Where: inside the VStack, directly after the closing } of the HStack · Action: Add
Spacer()
What it does: inserts a flexible gap that pushes the title row to the top of the screen.
Why it is written this way: a Spacer takes all the leftover vertical space in the VStack. With only one spacer, below the title, everything above the spacer is pushed to the top. The blank line before it is just for readability: it visually separates the "title" section of the code from the next section.
What should happen: the title row jumps to the top of the preview. That is the spacer at work.
Step 4 — Add the die display
File: ContentView.swift · Where: inside the VStack, directly after Spacer() · Action: Add
ZStack {
Circle()
.fill(Color.orange.opacity(0.2))
.frame(width: 160, height: 160)
Text("6")
.font(.system(size: 72, weight: .bold))
}
What it does: creates a 160-point pale orange disc with a large bold "6" layered on top of it.
Why it is written this way:
- A
ZStacklayers its children. TheCirclecomes first, so it is at the back; theTextcomes second, so it is in front. - The circle gets an explicit frame because shapes have no natural size. Without the frame, the circle would expand to fill all available space.
- The pale fill (
opacity(0.2)) gives the number a soft backdrop without competing with it. - The number uses an explicit 72-point bold system font, larger than any standard text style.
- The "6" is a placeholder. In Chapter 4 it becomes the actual roll result.
What should happen: with the title at the top and nothing yet below the die, the circle sits at the bottom of the screen, because the spacer above it pushes everything after it down. That is expected; the second spacer in Step 6 will bring it to the middle.
Suppose you moved the Text("6") and its modifier above the Circle() lines inside the ZStack, so the text came first. What would you see in the canvas? Decide, then try it, then move the lines back. The answer is in Prediction Answers.
Step 5 — Add the caption
File: ContentView.swift · Where: inside the VStack, directly after the closing } of the ZStack · Action: Add
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
What it does: adds a short instruction under the die display, in a muted secondary color.
Why it is written this way: the caption is supporting text, not the main event, so it uses the secondary style, which SwiftUI renders in an appropriate muted color for Light or Dark Mode. It has no .font modifier, so it uses the default body text style. In Chapter 4 this caption changes to tell the user which die is being rolled.
What should happen: the caption appears under the circle, in gray.
Step 6 — Add the second spacer and the button
File: ContentView.swift · Where: inside the VStack, directly after the caption's .foregroundStyle(.secondary) line · Action: Add
Spacer()
Button("Roll Dice") {
print("Roll Dice tapped")
}
What it does: adds a second flexible gap and a button at the bottom of the column. When the button is tapped, its action closure runs and prints "Roll Dice tapped" to the debug console.
Why it is written this way:
- Two spacers share the leftover space equally, so the die display and caption float in the middle while the title stays at the top and the button at the bottom.
- The button's title and action are kept short and obvious. The
printis temporary scaffolding: its only job is to prove the tap reaches your code. In Chapter 4 you replace it with the code that actually rolls. - The trailing closure form keeps the action readable.
What should happen: the canvas now shows the full layout: title at the top, the die display in the middle with the caption below it, and a plain blue "Roll Dice" text button at the bottom. It is blue because buttons use the app's accent color by default. The next step styles it.
Step 7 — Style the button
File: ContentView.swift · Where: directly after the closing } of the Button's action closure, at the same indentation as the word Button · Action: Add
.font(.title2)
.buttonStyle(.borderedProminent)
.controlSize(.large)
.tint(.orange)
What it does: turns the plain text button into a large, filled, orange button with a bigger title.
Why it is written this way:
- The modifiers attach to the whole
Button, so they start on the line after the button's closing brace, at the same indentation asButton. Indenting them that way makes it obvious that they modify the button, not theprintline inside it. .font(.title2)makes the label larger than body text but smaller than the title, so the button reads as the main action without shouting..borderedProminentis the system's style for the primary action on a screen: a filled shape behind the title. It automatically provides pressed, disabled and Dark Mode appearances..controlSize(.large)gives the button more padding, making it a comfortable thumb target..tint(.orange)colors the fill, matching the orange icon and die disc.
System button styles follow the design language of the iOS version they run on. Depending on whether your simulator runs an older or newer iOS, the prominent button may appear as a rounded rectangle or as a capsule with a glassy finish. Both are correct; you get the current system look for free.
What should happen: the canvas shows a large orange button with white "Roll Dice" text at the bottom of the screen.
Step 8 — Leave the padding in place and check the whole file
The .padding() modifier after the VStack's closing brace stays exactly as it was. It keeps the title and button away from the screen edges. You do not need to change it.
Your complete ContentView structure should now read:
struct ContentView: View {
var body: some View {
VStack(spacing: 24) {
HStack {
Image(systemName: "dice.fill")
.font(.title)
.foregroundStyle(.orange)
Text("Dice Foundry")
.font(.largeTitle)
.fontWeight(.bold)
}
Spacer()
ZStack {
Circle()
.fill(Color.orange.opacity(0.2))
.frame(width: 160, height: 160)
Text("6")
.font(.system(size: 72, weight: .bold))
}
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
Spacer()
Button("Roll Dice") {
print("Roll Dice tapped")
}
.font(.title2)
.buttonStyle(.borderedProminent)
.controlSize(.large)
.tint(.orange)
}
.padding()
}
}
The import SwiftUI line above it and the #Preview block below it are unchanged.
Step 9 — Build, run and tap
- Press ⌘B to build. The build should succeed with no errors and no warnings. If the Issue navigator shows anything, see Troubleshooting.
- Choose an iPhone simulator in the toolbar's run destination menu if one is not already selected, then press ⌘R.
- When the app appears, press ⇧⌘Y if the debug area is not visible, and make sure the console pane is showing.
- Tap Roll Dice in the Simulator. Each tap should add one line to the console.
You launch the app with ⌘R and do not touch anything for a few seconds. Then you tap Roll Dice three times. How many lines reading "Roll Dice tapped" are in the console after launch but before the first tap, and how many after the third tap? Write down your answer and the reason, then check it in the Simulator.
Step 10 — Experiment with modifier order (then undo)
This step is an experiment. It changes nothing permanently.
File: ContentView.swift · Where: directly below the caption's .foregroundStyle(.secondary) line · Action: Add (then Delete at the end of this step)
Text("Tap Roll Dice to begin")
.foregroundStyle(.secondary)
.padding()
.background(Color.orange)
Type only the last two lines; the first two are already there.
- In the canvas, find the caption "Tap Roll Dice to begin".
- Add the two experiment lines shown above,
.padding()and then.background(Color.orange). Look at the canvas. - Swap the two new lines so
.background(Color.orange)comes first. Look again. - Delete both new lines so the caption is back to its original two lines.
You should see a roomy orange box around the caption in step 2, and a tight orange strip with no visible padding in step 3, exactly as described in "Modifier order matters." Make sure you delete the experiment lines before you commit.
Expected Results
When you run the app, the screen should look like this:
Illustrative mockup — not a screenshot
+----------------------------------+
| |
| [dice] Dice Foundry | <- orange icon, bold large title
| |
| |
| .------. |
| / \ |
| | 6 | | <- pale orange disc, big bold 6
| \ / |
| '------' |
| Tap Roll Dice to begin | <- gray caption
| |
| |
| [ Roll Dice ] | <- large orange filled button
| |
+----------------------------------+

Figure: the Chapter 3 screen on first launch in light appearance, with the orange icon and title, the die showing 6, the caption and the Roll Dice button. The 6 is fixed in this chapter; in later chapters, rolled numbers will differ on your device.
The title row is centered horizontally at the top, the die display and caption are in the middle, and the button is at the bottom. On a larger iPhone the gaps grow; on a smaller one they shrink. In Dark Mode (in the Simulator: Features → Toggle Appearance, or Settings → Developer → Dark Appearance) the background turns black, the title turns white, and the caption stays readable because .secondary adapts.
After three taps on Roll Dice, the debug console should contain:
Roll Dice tapped
Roll Dice tapped
Roll Dice tapped
The console may also contain system messages from iOS or Xcode. Those are normal and can be ignored; look for your own lines.
The die always shows 6. That is correct for this chapter: nothing in the code changes it yet.
Reading This Like a Developer
You now have enough code on the screen to practice reading it the way an experienced developer would. Ask the questions below of any SwiftUI project, and answer them for Dice Foundry.
Where does execution begin? At @main in DiceFoundryApp.swift. iOS launches the process, Swift finds the type marked @main (DiceFoundryApp), and SwiftUI reads its body, which contains a WindowGroup. The WindowGroup's trailing closure creates ContentView(). SwiftUI then reads ContentView's body, gets back the VStack description, and draws the screen. You did not write any code that "starts" ContentView; you declared it as the window's content, and SwiftUI did the rest.
iOS launches the app process
-> @main struct DiceFoundryApp
-> body: WindowGroup { ContentView() }
-> ContentView.body
-> VStack(...) { HStack, Spacer, ZStack, Text, Spacer, Button }
-> SwiftUI draws the screen
Which code runs when the button is pressed? Only the closure attached to the button: print("Roll Dice tapped"). The rest of body does not run again, because nothing it depends on has changed. This is worth stating plainly because it surprises people: tapping a button does not re-run your view code unless the tap changes some data the view reads. In Chapter 4, the tap changes data, and then you will see body re-run.
Which variables hold state? None yet. body is computed, not stored, and the "6" is a literal written into the code. A static interface has no state. Chapter 4 adds the first state variable.
Where does a value originate? Every value on screen is a literal in the source code: the strings "Dice Foundry", "6", "Tap Roll Dice to begin" and "Roll Dice", the numbers 24, 160 and 72, the colors. Nothing is calculated, loaded or entered by the user.
How does the interface respond to changes? In this version, it responds only to system changes such as Dark Mode, rotation or the user's text size (the text styles adapt; the explicit 72-point number does not). SwiftUI handles all of these without any code from you, because the body describes roles (.secondary, .largeTitle) rather than fixed pixels and colors.
Where is data saved? Nowhere. There is no data yet. Persistence arrives in Chapter 9.
Business logic versus presentation logic. Everything in this chapter is presentation: decisions about what the screen looks like. There is no business logic (the rules of the app's domain, such as "a six-sided die produces a number from 1 to 6") yet. Keeping the two separate becomes a theme of the course; for now, notice that body should only ever contain presentation, and that the button's action closure is where behavior will go.
When you open an unfamiliar SwiftUI file, collapse the noise by reading only the lines that start a view (VStack, HStack, Text, Button ...) and ignoring the modifier lines that start with a dot. The indentation of those view lines is the view hierarchy. Then go back and read the modifiers for each view you care about.
Troubleshooting
Type 'ContentView' does not conform to protocol 'View'
Type 'ContentView' does not conform to protocol 'View'
What it means: ContentView promised to conform to View but does not provide a valid body.
Likely causes:
bodyis misspelled (Body,bdy,boddy).someis missing:var body: View {. In this case you may also see a warning similar to "use of protocol 'View' as a type must be written 'any View'."- A brace is missing or extra, so the compiler thinks
bodyhas ended (or never started) somewhere other than you intended.
How to investigate: look at the var body: some View { line character by character. Then check braces: click just after each { and } and watch which brace Xcode highlights as its partner. Select the whole file and press ⌃I to re-indent; if the indentation suddenly looks wrong partway through the file, the brace problem is just above that point.
Value of type 'Text' has no member 'foregroundstyle'
Value of type 'Text' has no member 'foregroundstyle'
What it means: you called a modifier that does not exist on that view. Swift names are case-sensitive, so foregroundstyle and foregroundStyle are different names, and only the second exists.
Likely causes: a capitalization mistake or a typo in a modifier name, or a modifier that belongs to a different kind of view (for example .fill exists on shapes such as Circle, not on Text).
How to investigate: delete the modifier name after the dot and start typing it again slowly; Xcode's code completion lists only the modifiers that exist. Accepting a completion guarantees the spelling.
Errors about braces, or errors at the end of the file
If you delete or add a brace by mistake, the compiler often reports errors far from the real problem, frequently at the very end of the file, with messages similar to "Expected '}' in struct" or "Extraneous '}' at top level."
How to investigate: the actual mistake is usually where the indentation stops matching the structure. Select all (⌘A) and re-indent (⌃I). Scroll through the file and find the first place where the indentation looks wrong. Compare that region with the complete listing in Step 8.
The icon does not appear
The project builds and runs, but there is a gap where the dice icon should be.
What it means: Image(systemName:) was given a name that does not match any SF Symbol. The compiler cannot check strings, so this is a run-time problem.
Likely causes: a typo ("dice.fil", "Dice.fill", "dice-fill").
How to investigate: run the app (⌘R) and look in the debug console for a message similar to "No symbol named 'dice.fil' found in system symbol set." Then open the SF Symbols app, search for the symbol, and copy its exact name.
Tapping the button prints nothing
Likely causes and checks:
- You are tapping in the preview canvas rather than in the Simulator. Run with ⌘R and tap in the Simulator window.
- The debug area is hidden. Press ⇧⌘Y.
- The debug area shows only the variables pane. Use the small buttons at the bottom right of the debug area to show the console.
- The console's filter field (at the bottom of the console) contains text, hiding your lines. Clear it.
- The
printline is outside the button's braces. It must be inside the closure that followsButton("Roll Dice").
The preview is paused or shows an error
The canvas can stop updating after a build error, or show a message that the preview failed or crashed.
How to investigate:
- Fix any errors shown in the editor first. Previews cannot run code that does not compile.
- Press ⌥⌘P to resume.
- If the canvas offers a diagnostics button, click it; the details usually name the real error.
- As a last resort, choose Product → Clean Build Folder (⇧⌘K), then build (⌘B) and resume the preview.
The layout looks wrong
Symptoms and likely causes:
- Everything is bunched at the top or bottom: one of the two
Spacer()lines is missing, or both are on the same side of the die display. - The circle fills the whole screen: the
.frame(width: 160, height: 160)line is missing or attached to the wrong view. - The number looks faded or tinted orange: inside the
ZStack, theTextcomes before theCircle, so the semi-transparent circle is drawn over it. The first child is at the back. - The icon is above the title instead of beside it: the
ImageandTextare not inside theHStack's braces. - An error similar to "Value of tuple type '()' has no member 'font'" on the button: the button modifiers are inside the action closure instead of after its closing brace, so Swift tries to apply
.fontto the result ofprint(...), which is an empty value, not a view. Move the four modifier lines below the closing}of the action.
How to investigate: in the canvas, switch to Selectable mode and click the element that looks wrong. Xcode highlights the code that produced it. Then check which container that code is really inside.
Knowledge Check
- In your own words, what does
struct ContentView: Viewdeclare, and what does the: Viewpart promise? - What does
some Viewmean, and why do SwiftUI views use it instead of writing the exact type of thebody? - Explain why the code in this chapter contains no instructions to redraw the screen, and what SwiftUI does instead when data changes.
- In a
ZStack, which child appears in front? Why did we putCircle()beforeText("6")? - Why does
Text("Dice").padding().background(Color.orange)look different fromText("Dice").background(Color.orange).padding()?
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.
Independent challenges let you practice without step-by-step instructions. Do them on a separate Git branch (see the Exercises document for the commands), so your guided project stays identical to the reference checkpoint. Progressive hints are in the Chapter 3 Exercises document, and solutions are in the Chapter 3 Answers document.
Later chapters add a die picker, a quantity and a modifier. Preview that future by adding a static strip of three labels between the caption and the second spacer. The labels read "D6", "1 die" and "Modifier +0", side by side with 12 points between them. Each label uses the headline text style, has 8 points of padding on every side, and has a pale orange background (Color.orange.opacity(0.2)) that covers its padding. Acceptance criteria: the three labels appear in a row under the caption; each label's orange area includes the padding around the text, not just the letters; the rest of the layout is unchanged; the project builds with no errors or warnings.
Without looking at the hierarchy diagram in this chapter, draw the view hierarchy of your finished Challenge 1 screen as an indented text tree, including the new strip. Then mark each view as a container (it holds children) or a leaf (it does not). Acceptance criteria: every view in body appears exactly once, at the correct depth, in the same order as in the code.
Chapter Completion Checklist
- I can explain what a view is and why it is a lightweight description.
- I can explain what
struct,: View,bodyandsome Viewmean inContentView. - I can explain the difference between declarative and imperative UI, and why I do not write redraw code.
- I can draw the view hierarchy of
ContentViewas a tree. - I can explain what
VStack,HStack,ZStackandSpacerdo, and why the circle needs a frame. - I can explain why modifier order matters, using padding and background as the example.
- I can recognize trailing closure syntax in
Button,VStack,WindowGroupand#Preview. - I know how to find an SF Symbol name in the SF Symbols app.
- The app runs and shows the title, die display, caption and orange Roll Dice button.
- Tapping Roll Dice in the Simulator prints "Roll Dice tapped" in the debug console.
- I removed the modifier-order experiment lines from Step 10.
- The project builds with no errors or warnings.
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, enter the message below, and commit. Or in Terminal, from your project folder:
git add -A
git commit -m "Chapter 3: Static Dice Foundry interface"
git tag chapter-03
If you deleted SwiftPractice.swift, git add -A records the deletion too.
To compare with the reference, open Reference-Checkpoints/Checkpoint-03-Static-Interface/DiceFoundry/ and compare ContentView.swift with yours. You can use FileMerge (Xcode → Open Developer Tool → FileMerge) or Terminal:
diff -u Reference-Checkpoints/Checkpoint-03-Static-Interface/DiceFoundry/ContentView.swift \
/path/to/your/DiceFoundry/DiceFoundry/ContentView.swift
Differences in comments or the file header are fine. SwiftPractice.swift exists only in your project if you kept it; that is fine too. Any difference inside body is worth understanding before you move on, because Chapter 4 edits these exact lines.
Prediction Answers
Which area turns orange? With .frame(width: 160, height: 160) before .background(Color.orange), the background wraps the 160 by 160 frame, so you see a full orange square with the "6" centered in it. With .background(Color.orange) first, the background wraps only the text's natural size, so only a small rectangle the size of the "6" is orange; the frame is then applied around that small orange view, adding transparent space. The background covers whatever it wraps, and what it wraps is everything above it in the chain.
Swap the layers. Perhaps surprisingly, you would see almost the same thing. The "6" is now behind the circle, because a ZStack draws its first child at the back and each later child on top. But the circle's fill is only 20 percent opaque, so the number shows through it, looking slightly washed out and tinted orange. Change the fill to a fully opaque Color.orange while the text is first and the number disappears completely. That is the real lesson: in a ZStack, order decides what is in front, and transparency decides whether you can still see what is behind. Put the Circle() lines back first, and the fill back to Color.orange.opacity(0.2).
Count the lines. Zero lines before the first tap, and three after the third tap. The print is inside the button's action closure, and SwiftUI runs that closure only when the button is tapped. Drawing the screen at launch reads body, which creates the button and hands it the closure, but does not run the closure. Each tap runs it once. (You may see unrelated system messages in the console; they are not yours.)