Dice Foundry Student Workbook

Chapter 2 — Swift Fundamentals

In Chapter 1 you ran an app, but you did not write any Swift that a computer had to think about. The words "Dice Foundry" and the dice icon were literals placed in a view. In this chapter you learn the language itself, one idea at a time: how to make the computer print a message, how to store a value with a name, how numbers and words differ, how to combine them with operators, and how to deal with a value that might be missing.

You will practice in a playground. A playground is a place where Swift code runs immediately and shows its results, without building the whole app. It is the fastest way to learn a language, and it is the same tool many professional developers use to test an idea before they write it into an app. Chapter 3 returns to the app and starts building the interface you saw in Chapter 1.

Everything in this chapter is practice. The code you write goes into a separate file, SwiftPractice.swift, that lives in the project but does not change the app's screen. You can keep the file or delete it at the end of the course; the app will not depend on it.

Learning Objectives

By the end of this chapter you will be able to:

  • Explain what a statement and an expression are, and how Swift reads a file from top to bottom.
  • Write comments with // and explain why they matter when reading AI-generated code.
  • Declare constants with let and variables with var, and explain why let is the default.
  • Give a value a type with a type annotation, and explain when Swift infers the type for you.
  • Use the basic types Int, Double, String and Bool, and explain the difference between Int and Double.
  • Use arithmetic (+ - * /), comparison (== > <), assignment (=) and compound assignment (+=) operators.
  • Insert a value into a string with \( ) interpolation.
  • Convert between Int and Double with Double(...).
  • Explain what an optional is, and use nil, if let, ?? and Int("12") to handle values that may be missing.
  • Explain how braces { } create a scope, and why a name declared inside one block is not visible in another.
  • Read a code-tracing exercise and predict the output before running it.

Concept Explanation

Statements, expressions and the order of execution

A statement is one complete instruction. Swift reads a file from top to bottom, and runs statements in that order. A statement can be as small as print("Hello, World") or as large as a block that contains many other statements.

An expression is code that produces a value. 2 + 3 is an expression whose value is 5. "Dice" + " Foundry" is an expression whose value is a longer string. An expression can appear inside a statement. In let total = 2 + 3, the expression 2 + 3 produces 5, and the statement stores that value under the name total.

Most lines in Swift are statements. A few are declarations, which introduce a name, such as let total = 5 or struct ContentView. Declarations are also statements in the broader sense: they tell Swift that a name exists and what it means.

Infrastructure Analogy: Statements are like a runbook

A runbook is read top to bottom. Each step either does something (restart a service, copy a file) or records a result for a later step. A statement is the same kind of instruction, and a file of Swift is a runbook the computer executes in order. If step 4 uses a value that step 2 never recorded, the runbook fails at step 4. Swift does the same: a name must be declared before it is used.

Comments

A comment is text that Swift ignores. Two forward slashes start a comment that runs to the end of the line:

Example — not part of the Dice Foundry project
// This line is a comment, and Swift does not run it.

Comments explain why, not what. The code already says what it does. A good comment tells the reader something the code cannot say on its own: the reason for a choice, an assumption, or a warning. You will see this in the practice file: // Int? because the text might not be a number explains a type choice that would otherwise look odd.

AI-Assisted Development: Read AI-generated code by its comments

AI assistants often add comments that restate the code ("// add one to the counter"). Those comments are cheap and add little. The valuable comments are the ones that explain a decision: why a value is clamped, why a function returns an optional, why something runs on the main thread. When you review generated code, check whether the comments explain decisions. If a comment disagrees with the code below it, trust the code and fix the comment.

Constants and variables: let and var

Swift stores values under names. There are two ways to declare a name:

  • let declares a constant. Once the value is set, it cannot change. let appName = "Dice Foundry" creates a name that always refers to that string.
  • var declares a variable. Its value can change later. var rollCount = 0 creates a name whose value can be replaced, for example by rollCount = rollCount + 1.

Swift encourages let. If a value never changes, let tells the reader and the compiler that it will not change. If you try to change a let, the compiler reports an error and the code does not build. Use var only when you need the value to change.

Tip: Start with let and change to var when the compiler asks

A good habit is to write let first. When the compiler says "cannot assign to value: 'x' is a 'let' constant," change the declaration to var. This keeps your code honest about what changes and what does not.

Types: what kind of value a name holds

Every value in Swift has a type, which says what kind of value it is and what you can do with it. The type determines which operations are allowed. You can add two numbers, but you cannot add a number to a whole sentence without converting it first.

The basic types in this chapter are:

Type Holds Example
Int Whole numbers, positive, negative or zero 6, -2, 0
Double Numbers with a fractional part 3.5, 0.25
String Text "Dice Foundry"
Bool True or false true, false

When you write let sides = 6, Swift looks at the 6, sees a whole number, and decides the type is Int. This is type inference. When you want to be explicit, you write the type after a colon: let sides: Int = 6. This is a type annotation. Both lines mean the same thing. Annotations are most useful when you want a different type from the one Swift would infer, such as a Double holding a whole number: let average: Double = 4.

Int and Double are different types

Int and Double cannot be mixed directly in an expression. Int holds whole numbers only; Double holds a fractional part as well. Swift refuses to combine them automatically, because the result might lose precision, and the compiler wants you to say what you mean.

Example — not part of the Dice Foundry project
let rolls = 3
let average: Double = 3.5
let total = rolls * average   // error: cannot combine Int and Double

The fix is to convert explicitly: Double(rolls) * average. The expression Double(rolls) creates a new Double from the Int, and multiplication then works. You will see this conversion in the practice file.

Infrastructure Analogy: Explicit conversion is like a typed API contract

A well-designed API rejects a string where it expects an integer and does not guess. Swift's strict typing does the same for every value. The conversion Double(rolls) is the explicit step where you tell the compiler you accept the change of representation. This strictness is annoying for a few hours and then becomes a safety net: most type errors show up in the editor, not in production.

Operators

An operator is a symbol that combines values. The common ones:

Kind Operators Example Result
Arithmetic +, -, *, / 2 + 3 5
Comparison ==, !=, >, <, >=, <= 6 > 10 false
Assignment = total = 5 stores 5 in total
Compound assignment +=, -= rollCount += 1 adds 1 to rollCount

Two points deserve emphasis. The equal sign = stores a value; the double equal sign == compares two values and gives a Bool. Mixing them up is one of the most common beginner mistakes, and the compiler reports it. The compound operator += is shorthand: rollCount += 1 means the same as rollCount = rollCount + 1.

String interpolation

Inside a string, \( ) inserts the value of an expression. The expression is evaluated, converted to text, and placed into the string:

Example — not part of the Dice Foundry project
let name = "Dice Foundry"
let rolls = 2
let message = "\(name) has rolled \(rolls) times"   // "Dice Foundry has rolled 2 times"

Interpolation is how the course builds every piece of text that changes. You will see it in every chapter from here on.

Optionals: values that may be missing

Sometimes a value might not exist. A user might not have chosen a favorite die. A piece of text the user typed might not be a number. Swift handles this with an optional, a type that is either a value or nil (nothing).

An optional is written with a question mark after the type: String? means "a string, or nothing." Int? means "an integer, or nothing." A value of type String? is not a String, and you cannot use it as one until you check whether it contains a value.

Three tools handle optionals:

  • if let unwraps an optional when it has a value, and runs the block only in that case.
  • ?? (the nil-coalescing operator) provides a default value when the optional is nil.
  • Int("12") tries to read a whole number from a string. It returns an Int?, because the string might not contain a number.
Example — not part of the Dice Foundry project
let typed: String? = "12"
let number = Int(typed ?? "0")   // an Int? value
Infrastructure Analogy: An optional is a null that the compiler makes you handle

In many languages a missing value is a null that can appear anywhere, and the crash happens later when someone uses it. Swift puts the possibility of "nothing" into the type itself, so the compiler knows where it might appear. This is the same principle as a well-designed alerting rule: the check that could fail is written down where the failure can happen, not discovered in production.

Scope: the braces that define where a name lives

A pair of braces { } creates a scope. A name declared inside a scope exists only inside it. When the closing brace is reached, the names disappear. Each #Playground block in the practice file has its own scope, so a name declared in one playground is invisible in another.

This matters later in the app. A name declared inside a body property is not visible to other properties. You will see scope more clearly in Chapter 4.

Declare, initialize, assign and read

Four actions cover almost everything that happens to a name:

  1. Declare a name: var rollCount (this introduces the name, but a variable must have a value before you read it).
  2. Initialize it: var rollCount = 0 (the first value).
  3. Assign a new value: rollCount = 1.
  4. Read it: print(rollCount).

Swift requires a value before reading. var rollCount: Int alone, followed by print(rollCount), is an error. The compiler will not let you read a name that has never been given a value.

Syntax Breakdown

The first complete program in this chapter is one line. Here is the first thing you will type, in a playground:

Example — not part of the Dice Foundry project
print("Hello, World")
Token Meaning
print A function built into Swift that writes its arguments to the output. A function is a named piece of behavior.
( and ) Round brackets enclose the arguments passed to the function.
"Hello, World" A String literal. The quotation marks say "this is text, not a name."

Read it as: "call the function print with the string Hello, World." The statement is complete and runs by itself.

The practice file uses more syntax. Here is the first declaration from the reference file:

Dice Foundry code
    let appName = "Dice Foundry"
Token Meaning
let Declares a constant. The value cannot change after it is set.
appName The name. Lowercase first letter, camel case for multiple words.
= Assigns the value on the right to the name on the left. This is the initialization.
"Dice Foundry" The String value. Swift infers the type String from the literal.

Here is a variable that changes:

Dice Foundry code
    var rollCount = 0
    rollCount = rollCount + 1
    rollCount += 1
Token Meaning
var Declares a variable, a value that can change.
rollCount = 0 Declares and initializes rollCount as an Int with value 0.
rollCount = rollCount + 1 Reads the current value (0), adds 1, and stores 1 back into rollCount.
rollCount += 1 Shorthand for the line above. Adds 1 and stores the result. After this line rollCount is 2.

The type annotation form uses a colon:

Dice Foundry code
    let sides: Int = 6
Token Meaning
sides The constant's name.
: Introduces a type annotation. Read it as "is of type."
Int The type: a whole number.
= 6 Initializes the constant.

The optional forms use a question mark and nil:

Dice Foundry code
    var favoriteDie: String? = nil
Token Meaning
var The value can change later.
favoriteDie The name.
String? The type: a string or nothing.
= nil Starts with no value.

Guided Implementation

In this chapter you create one file and fill it in step by step. Each playground runs separately in the canvas, so you can check each one before you move on. Use the Run control that appears beside each #Playground line in the editor. If you cannot find it, see Troubleshooting.

Step 1 — Create the practice file

Step 1 — Create SwiftPractice.swift

File: SwiftPractice.swift (new) · Where: the DiceFoundry folder in the navigator, next to ContentView.swift · Action: Create file

  1. In the navigator, right-click the DiceFoundry folder (the one that contains ContentView.swift).
  2. Choose New File…, then select Swift File under the Source category. Click Next.
  3. Name it SwiftPractice. Make sure the DiceFoundry target is checked. Click Create.

Xcode creates a new Swift file. Its contents may differ slightly from the next step; Step 2 replaces them.

Step 2 — Add the import for playgrounds

Step 2 — Write the header and the import

File: SwiftPractice.swift · Where: replace everything in the file · Action: Replace

Replace the file's contents with this code. The first lines are comments identifying the file. The import Playgrounds line lets the file use the #Playground blocks that you add next.

Dice Foundry code
//
//  SwiftPractice.swift
//  DiceFoundry
//

import Playgrounds

// Chapter 2 practice file.
// Code inside #Playground runs in Xcode's canvas, not in the app.

What it does: import Playgrounds makes the #Playground feature available in this file. The comments say what the file is for, so anyone who opens it later knows that nothing here affects the app.

Why this is written this way: a file in the app target is compiled into the app. Playground blocks are not part of the running app, so the import and the comment tell the reader and the compiler what the file is for. Xcode 26 or later is required for #Playground.

Step 3 — Write the first playground: Hello, World

Step 3 — Add the first playground

File: SwiftPractice.swift · Where: at the end of the file, after the comments · Action: Add

Add this block at the end of the file. Your own file may show slightly different indentation; keep the line breaks as they appear here.

Example — not part of the Dice Foundry project
#Playground("Hello, World") {
    print("Hello, World")
}

What it does: #Playground("Hello, World") declares a playground with a name. The braces contain the code that runs when you run the playground. The print call writes the text to the output.

Why it is written this way: a playground needs a name, so the canvas can show it, and a body in braces, so Swift knows where the code begins and ends. This block is an intermediate example: it is not part of the final reference file, and you may keep it or delete it when the chapter is done.

Now run it. Find the run control beside the #Playground line in the editor and click it. The canvas or the debug area should show the output:

Hello, World

If you see the message, you have written and run your first Swift program. Congratulations; this is the same thing every programmer writes first.

Predict Before You Run: Predict before you run

Change "Hello, World" inside print to "Hello, Dice" and run again. What appears? Now change print("Hello, Dice") to print("Hello, Dice", "Foundry"). What appears? Write both answers before you run.

Step 4 — Add the constants and variables playground

Step 4 — Add a playground with constants and variables

File: SwiftPractice.swift · Where: after the Hello, World block · Action: Add

Add this block below the first one:

Dice Foundry code
#Playground("Constants and variables") {
    let appName = "Dice Foundry"
    var rollCount = 0
    rollCount = rollCount + 1
    rollCount += 1
    let summary = "\(appName) has rolled \(rollCount) times"
    print(summary)
}

What it does, line by line:

  • let appName = "Dice Foundry" creates a constant. The name never changes after this line.
  • var rollCount = 0 creates a variable starting at zero.
  • rollCount = rollCount + 1 reads the current value (0), adds one, and stores 1.
  • rollCount += 1 adds one more. The value is now 2.
  • let summary = "\(appName) has rolled \(rollCount) times" builds a string. Interpolation inserts the current value of each name.
  • print(summary) writes the result.

Why it is written this way: the block shows three ideas in the order a program would use them: a constant, a changing variable, and a string built from both. The let for appName is correct because the name does not change. The var for rollCount is correct because the count does change.

Run the playground. The output should be:

Dice Foundry has rolled 2 times

Check the arithmetic yourself: the count started at 0, went up once with rollCount = rollCount + 1, and up once more with rollCount += 1. That is 2.

Predict Before You Run: Predict the output

Add the line rollCount = 10 after rollCount += 1 and before let summary. What does the output say now? Write your answer, then run.

Step 5 — Add the numbers and types playground

Step 5 — Add a playground with numbers and types

File: SwiftPractice.swift · Where: after the Constants and variables block · Action: Add

Dice Foundry code
#Playground("Numbers and types") {
    let sides: Int = 6
    let average: Double = 3.5
    let rolls = 3
    let expectedTotal = Double(rolls) * average
    let isBigDie = sides > 10
    print(expectedTotal, isBigDie)
}

What it does, line by line:

  • let sides: Int = 6 declares a constant with an explicit type annotation.
  • let average: Double = 3.5 declares a Double, a number with a fractional part.
  • let rolls = 3 has no annotation; Swift infers Int.
  • let expectedTotal = Double(rolls) * average converts rolls to a Double and multiplies it. The result is 10.5.
  • let isBigDie = sides > 10 compares two values. The result is a Bool: false, because 6 is not greater than 10.
  • print(expectedTotal, isBigDie) writes both values, separated by a space.

Why it is written this way: the line Double(rolls) * average is the one that matters most. Without Double(...), the expression would not compile, because Int and Double cannot be multiplied directly. The conversion is explicit so the reader can see the change of type.

Run it. The output should be:

10.5 false
Try the broken version (optional)

Temporarily replace Double(rolls) * average with rolls * average. Run the playground. The editor shows an error similar to "Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'." Put the conversion back before you continue.

Step 6 — Add the manual dice total playground

Step 6 — Add a playground that adds three dice by hand

File: SwiftPractice.swift · Where: after the Numbers and types block · Action: Add

Dice Foundry code
#Playground("Manual dice total") {
    // Rolling 3D6 + 2 by hand: the dice showed 4, 2 and 6.
    let firstDie = 4
    let secondDie = 2
    let thirdDie = 6
    let modifier = 2

    let subtotal = firstDie + secondDie + thirdDie
    let total = subtotal + modifier
    print("3D6 + \(modifier): \(firstDie), \(secondDie), \(thirdDie) = \(total)")
}

What it does: the three dice values and the modifier are constants. subtotal adds the dice, and total adds the modifier. The print line interpolates each value into a sentence.

Why it is written this way: the names describe the meaning. A reader can see that the dice total is the subtotal and the modifier is added separately. This is the same way you will name values in the app: a name that says what the number is, not what it holds.

Run it. The output should be:

3D6 + 2: 4, 2, 6 = 14

Check it by hand: 4 + 2 + 6 is 12, and 12 + 2 is 14.

Predict Before You Run: Predict the total

Change modifier from 2 to -3. What does the last line print? Predict the total before you run it.

Step 7 — Add the optionals playground

Step 7 — Add a playground with optionals

File: SwiftPractice.swift · Where: after the Manual dice total block · Action: Add

Dice Foundry code
#Playground("Optionals") {
    var favoriteDie: String? = nil
    favoriteDie = "D20"

    if let die = favoriteDie {
        print("Your favorite die is the \(die)")
    } else {
        print("You have no favorite die yet")
    }

    let typedText = "12"
    let number = Int(typedText)      // Int? because the text might not be a number
    let safeNumber = number ?? 0
    print(safeNumber)
}

What it does:

  • var favoriteDie: String? = nil starts with no value, and the type allows nothing.
  • favoriteDie = "D20" stores a value.
  • if let die = favoriteDie checks whether a value is present. If so, die is a plain String, and the first print runs. Otherwise the else branch runs.
  • Int(typedText) tries to read a whole number from the string. It returns an Int?, because the string might not contain a number.
  • number ?? 0 uses the number if it exists, and 0 if it is nil.

Why it is written this way: the if let and ?? forms are how Swift makes you handle a missing value before you use it. In this example both branches are safe, and the compiler checks that.

Run it. The output should be:

Your favorite die is the D20
12
Predict Before You Run: Predict the branch

Add the line favoriteDie = nil after favoriteDie = "D20". Which message prints now? Write your answer, then run.

Step 8 — Check the whole file against the reference

Your SwiftPractice.swift now contains the header, the import and five playgrounds: the Hello, World block you added first, and the four reference blocks. Compare your file with the reference:

Reference-Checkpoints/Checkpoint-02-Swift-Fundamentals/DiceFoundry/SwiftPractice.swift

Your file should match the reference, except that it also contains the Hello, World block from Step 3. The reference omits that block. You may keep it, because it is harmless and it is the first program you wrote in Swift.

Expected Results

When you run each playground, the canvas or the debug area shows the output below. Your Xcode may show the results beside the code rather than in a separate panel; the text is the same.

Hello, World
Dice Foundry has rolled 2 times
10.5 false
3D6 + 2: 4, 2, 6 = 14
Your favorite die is the D20
12

If you run the whole app with ⌘R, nothing changes on the screen. The app does not run any of the playgrounds, and the dice icon and "Dice Foundry" text from Chapter 1 remain. This is correct: the practice file is separate from the app.

Illustrative mockup — not a screenshot:

+--------------------------------------------+
| SwiftPractice.swift                         |
|  #Playground("Numbers and types")  [Run]    |
|                                            |
|  Output:                                   |
|    10.5 false                              |
+--------------------------------------------+

Reading This Like a Developer

A playground is not an app, so the rules for tracing it are different from Chapter 1.

Where execution begins. Each #Playground block begins when you run it. Swift reads the block from top to bottom. Nothing in one block runs because of another, unless you run them together.

Which code runs when. Statements run in the order they are written. The value of each name is set at the line where it is declared and changed only when a later line assigns it. To trace a value, find its last assignment before the line you are reading.

Which variables hold state. In this chapter the state is inside each playground. rollCount holds state in the first playground; it is invisible in the others, because of scope.

Where a value originates and changes. Find the declaration first. var rollCount = 0 originates the value; rollCount = rollCount + 1 and rollCount += 1 change it. Read every line in order, and write down the value after each line. This is the skill that will let you read any function.

How data flows. Data flows from left to right in each expression, and from inner expressions to outer ones. In print("... \(total)"), the variable total is evaluated first, then interpolated into the string, then the string is passed to print.

Errors. The compiler reports errors before the code runs. Runtime errors (such as crashes from an unwrapped nil) are rare in these playgrounds, because if let and ?? handle the optional cases.

Business logic versus presentation. The playgrounds contain only logic, with print as the only output. Chapter 3 introduces the presentation side: views that display values on the screen.

Troubleshooting

The #Playground line shows an error such as "Cannot find 'Playground' in scope" or "Unknown macro." The import Playgrounds line is missing or misspelled, or your Xcode version is older than 26. Check Step 2 and confirm your Xcode version in the Xcode settings.

You cannot find the run control beside the #Playground line. Xcode displays the run control in the editor gutter, the narrow margin at the left of the code. Hover over the line to see it. If it is not visible, press ⌥⌘↩ to show the canvas, then look for the play control in its toolbar. Wording and placement may differ slightly on your version of Xcode. If you still cannot find it, do not guess: confirm that the playground block is inside a valid #Playground declaration, and check the Issue navigator for an error.

The message says something similar to "Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'." You are combining an Int and a Double directly. Add Double(...) around the Int value, as in Step 5.

The message says something similar to "Cannot assign to value: 'rollCount' is a 'let' constant." You declared the name with let and then tried to change it. Change the declaration to var.

The message says something similar to "Value of optional type 'Int?' must be unwrapped to a value of type 'Int'." You used an optional value as if it were a plain value. Unwrap it with if let, or provide a default with ??.

The message says something similar to "Cannot find 'appName' in scope." You are referring to a name declared in a different playground. Each playground has its own scope. Move the code into the same block, or declare the name again.

The playground shows no output. Check that your print call is inside the braces of the #Playground block, and that you ran that block and not another one. The output appears in the place Xcode uses for playground results on your version.

A line in the reference file looks different from yours. Whitespace differences are normal. The checker compares lines after trimming spaces, so indentation does not matter for correctness.

Knowledge Check

  1. Explain the difference between a statement and an expression, and give one example of each from this chapter.
  2. Why does Swift encourage let over var? What happens if you write let and then try to change the value?
  3. What does Double(rolls) * average do, and why is it needed when rolls is an Int?
  4. What is an optional? Name two tools for handling one, and say what each does.
  5. Why does a name declared inside one #Playground block not exist in another block?

Independent Challenge

Important: Commit before branching and switching

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.

Add one more playground block, named Expected total for 2D8 + 3, to SwiftPractice.swift. The block computes the expected total of rolling two eight-sided dice and adding a modifier of 3, then prints the result in a sentence.

Requirements:

  • Use let for every value that does not change.
  • Use an explicit Double for the average of one d8. The average of 1 through 8 is 4.5.
  • Calculate the expected total of two dice by converting an Int (the number of dice) to a Double before multiplying. Do not hard-code 9.0.
  • Add the modifier of 3.
  • Print one sentence that includes the sides, the number of dice, the modifier and the total, using string interpolation.
  • Expected output: a sentence whose total is 12.0.
  • The file builds with no errors and no warnings.

Do this on a branch so the guided project stays identical to the reference:

git switch -c challenge-02

When you finish:

git add -A
git commit -m "Challenge 02: Save practice work"
git status --short
git switch main

Progressive hints are in ch02-exercises.md. The solution is in ch02-answers.md.

Chapter Completion Checklist

  • I created SwiftPractice.swift in the DiceFoundry folder, with the DiceFoundry target checked.
  • I wrote the header comments and import Playgrounds.
  • I ran the Hello, World playground and saw Hello, World in the output.
  • I ran the Constants and variables playground and saw Dice Foundry has rolled 2 times.
  • I ran the Numbers and types playground and saw 10.5 false.
  • I ran the Manual dice total playground and saw 3D6 + 2: 4, 2, 6 = 14.
  • I ran the Optionals playground and saw Your favorite die is the D20 and 12.
  • I can explain why Double(rolls) is needed.
  • I can explain let, var, String?, if let, ?? and Int("12") in my own words.
  • I built the app with ⌘B and saw no errors.

Development Checkpoint

Save your work as a Git commit and tag it. From the project folder:

cd ~/Documents/DiceFoundryCourse/DiceFoundry
git add -A
git commit -m "Chapter 2: Swift fundamentals practice file"
git tag chapter-02

To compare your project with the reference for this chapter:

diff -r Reference-Checkpoints/Checkpoint-02-Swift-Fundamentals/DiceFoundry ~/Documents/DiceFoundryCourse/DiceFoundry/DiceFoundry

The differences you should see are the Hello, World playground you added in Step 3, and any Xcode-generated files. Everything else should match. The app code, ContentView.swift and DiceFoundryApp.swift, is unchanged from Chapter 1.

Prediction Answers

Predict, Step 3. Changing the text to "Hello, Dice" prints Hello, Dice. Changing the line to print("Hello, Dice", "Foundry") prints Hello, Dice Foundry. print separates multiple arguments with a space by default.

Predict, Step 4. Adding rollCount = 10 after the two increments sets the value to 10, so the output reads Dice Foundry has rolled 10 times. The earlier increments no longer matter, because the assignment replaces the value.

Predict, Step 6. With modifier = -3, the total is 12 - 3, which is 9. The last line prints 3D6 + -3: 4, 2, 6 = 9. The string interpolation prints the negative number with its sign.

Predict, Step 7. Adding favoriteDie = nil after favoriteDie = "D20" makes the optional empty again. The if let check fails, so the else branch runs and the output is You have no favorite die yet. The second line, 12, is unchanged.