Practice
Swift exercises
Make a change, predict what it will do, and compare the result.
- 1
Swift Basics
Bind a constant and print it.
Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.
Show starting example
Swiftlet name = "Ada" print("Hello, \(name)") - 2
Swift Functions and Argument Labels
Use default values and argument labels to make calls readable.
Predict greet("Cy", times: 0).
Reveal answer and reasoning
It returns an empty string, so print writes an empty line.
Show starting example
Swiftfunc greet(_ name: String, times: Int = 1) -> String { return Array(repeating: "Hi \(name)!", count: times).joined(separator: " ") } print(greet("Ada")) print(greet("Bo", times: 2)) - 3
Swift Optionals
Handle values that might be missing with if let.
Give failed conversions a default of 0.
Reveal answer and reasoning
Use let number = Int(text) ?? 0 and print number + 1 for every entry.
Show starting example
Swiftlet values = ["42", "x7"] for text in values { if let number = Int(text) { print("number \(number + 1)") } else { print("not a number: \(text)") } } - 4
Swift Structs
Model data with a struct, which is copied when assigned.
Predict the second result if y were set to 0 instead of x to 6.
Reveal answer and reasoning
The second call returns 9 + 0 = 9.
Show starting example
Swiftstruct Point { var x: Int var y: Int func distanceSquared() -> Int { return x * x + y * y } } var point = Point(x: 3, y: 4) print(point.distanceSquared()) point.x = 6 print(point.distanceSquared()) - 5
Swift Arrays
Grow an array and combine its values with reduce.
Use max() to find the highest score.
Reveal answer and reasoning
scores.max() returns an optional, Optional(95), because an empty array has no maximum.
Show starting example
Swiftvar scores = [82, 91, 76] scores.append(95) let total = scores.reduce(0, +) print(scores.count, total)