Chapter 2 Answers — Swift Fundamentals
Knowledge Check answers
1. Explain the difference between a statement and an expression, and give one example of each.
A statement is one complete instruction that Swift runs, such as print("Hello, World") or let total = 5. An expression is code that produces a value, such as 2 + 3 (which produces 5) or Double(rolls) * average. An expression can appear inside a statement: in let total = 2 + 3, the expression 2 + 3 produces 5, and the statement stores it.
2. Why does Swift encourage let over var? What happens if you write let and then try to change the value?
let declares a value that never changes, which tells the reader and the compiler that it is fixed. The compiler reports an error if you assign to a let, with a message similar to "cannot assign to value: ... is a 'let' constant." The fix is to change the declaration to var if the value really must change.
3. What does Double(rolls) * average do, and why is it needed when rolls is an Int?
Double(rolls) creates a Double from the Int value of rolls. The multiplication then combines two Double values and produces a Double. Swift does not convert Int to Double automatically in an expression, so the explicit conversion is required.
4. What is an optional? Name two tools for handling one, and say what each does.
An optional is a type that holds either a value of the underlying type or nil, which means no value. Written as String? or Int?. Tools include if let, which runs a block only when a value is present and gives you a plain value inside it, and ??, which supplies a default value when the optional is nil. Int("12") also returns an optional, because the text might not contain a number.
5. Why does a name declared inside one #Playground block not exist in another block?
Each pair of braces creates a scope, and a name exists only inside the scope where it is declared. When the closing brace is reached, the name goes away. Each playground has its own braces, so a name declared in one is not visible in the next.
Independent Challenge — Solution
Where the change goes
File: SwiftPractice.swift. Location: at the end of the file, after the last existing #Playground block. Action: add a new block. No other file changes.
The solution
#Playground("Expected total for 2D8 + 3") {
let sides = 8
let diceCount = 2
let modifier = 3
let averagePerDie: Double = Double(1 + sides) / 2
let expectedTotal = Double(diceCount) * averagePerDie
let withModifier = expectedTotal + Double(modifier)
print("Expected total for \(diceCount)D\(sides) + \(modifier): \(withModifier)")
}
The printed line is:
Expected total for 2D8 + 3: 12.0
Why it works
1 + sides is 9, the sum of the smallest and largest faces. Double(1 + sides) / 2 is 4.5, the average of one d8. The type annotation Double makes this a decimal division; without the conversion, the integer division of 9 by 2 would truncate to 4. Double(diceCount) * averagePerDie is 2.0 * 4.5, which is 9.0, the expected total of two dice. Adding the modifier, converted with Double(modifier), gives 12.0. The interpolation \(diceCount) and \(sides) inserts the values into the sentence.
Alternatives
You could write the average as 4.5 directly, which is simpler but hides the reasoning. You could also compute the expected total directly with Double(diceCount) * Double(1 + sides) / 2 + Double(modifier), which is shorter but harder to read; the course prefers named values, because they make the reasoning visible.
Verified: compiles with 0 errors and 0 warnings (Xcode 27.2, iOS 17.0 target). The verification run used the Checkpoint 02 project with the playground block above appended to SwiftPractice.swift; see the challenge-solutions folder.
Exercise answers
Exercise 1 — Predict the output.
- After
var score = 10andscore += 5,scoreis15. Thenscore = score - 3runs on the next line. - After the third line,
scoreis12. bonusis2, soscore + bonusis14. The output isScore: 14.
Exercise 2 — Spot the bug. The line let average = total / rolls divides a Double by an Int. Swift does not combine the two types implicitly, so it reports an error similar to "binary operator '/' cannot be applied to operands of type 'Double' and 'Int'." Rewrite the line as let average = total / Double(rolls). The result is 3.5, which prints as 3.5.
Exercise 3 — Trace the optional.
"7":Int("7")returns7, soparsedholds7,valueis7, and the output is7."seven":Int("seven")returnsnilbecause the text is not a whole number, sovalueis-1and the output is-1.""(empty string):Int("")returnsnil, so the output is-1.
Exercise 4 — Scope. The second playground reports an error similar to "cannot find 'secret' in scope." Each #Playground has its own braces, so the name declared in the first block does not exist in the second.
Exercise 5 — Read a comment. The reference file (Reference-Checkpoints/Checkpoint-02-Swift-Fundamentals/DiceFoundry/SwiftPractice.swift) contains this line: let number = Int(typedText) // Int? because the text might not be a number. Any shorter rewrite that still names the reason is a good answer, for example // nil if not a number. It remains useful because it explains why the value is optional, which the reader could not work out from the code alone. Comments should explain decisions the code cannot show.
Prediction answers in the chapter
The chapter has four inline predict exercises, in Steps 3, 4, 6 and 7. Short versions of their answers are repeated here for reference. The full answers are in the chapter's Prediction Answers section.
- Step 3.
"Hello, Dice"printsHello, Dice. Adding a second argument,print("Hello, Dice", "Foundry"), printsHello, Dice Foundrybecauseprintseparates its arguments with a space. - Step 4. Setting
rollCount = 10after the increments makes the outputDice Foundry has rolled 10 times, because the assignment replaces the earlier values. - Step 6. With
modifier = -3, the total is 12 − 3 = 9, and the last line prints3D6 + -3: 4, 2, 6 = 9. - Step 7. Setting
favoriteDie = nilafter"D20"makes theif letfail, so theelsebranch printsYou have no favorite die yet.