Activity 1
Handle a failable conversion
Convert the strings “28” and “twenty” to Int values and explain why the results have the same optional type but different contents.
Hint: Print or bind each result rather than force unwrapping it.
Swift Fundamentals
Model missing values explicitly and unwrap them safely with binding, guard, chaining, and defaults.
Before you begin
Learning stage
An optional represents either a value of a specific wrapped type or no value. Write a question mark after the type, such as Int? or String?. The absence of a value is written nil.
Swift requires code to handle absence before using the wrapped value. Optional binding unwraps conditionally, optional chaining propagates absence, and the nil-coalescing operator supplies a fallback.
Learning stage
A failable conversion produces an optional Int, which is safely unwrapped before use.
let input = "42"
let parsedScore = Int(input)
if let score = parsedScore {
print("Score: \(score)")
} else {
print("Enter a valid number")
}
let nickname: String? = nil
let displayName = nickname ?? "Learner"
print("Welcome, \(displayName)")Learning stage
These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.
Learning stage
Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.
Learning stage
Work through these activities in a small Xcode project. No embedded playground is required on this site.
Activity 1
Convert the strings “28” and “twenty” to Int values and explain why the results have the same optional type but different contents.
Hint: Print or bind each result rather than force unwrapping it.
Activity 2
Create optional firstName and nickname values. Choose a fallback order that always produces a display name.
Hint: You can chain multiple ?? operations.
Learning stage
Answer each question before revealing the explanation.
QUESTION 1
A String or nil
The wrapped type remains specific even though the value may be absent.
QUESTION 2
The program triggers a runtime error.
Use ! only when the program has a genuine invariant that proves the value exists.
QUESTION 3
It returns the wrapped value when present, otherwise it returns the fallback.
Learning stage
Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.
Short answer: Optionals make the possible absence of a value explicit in the type system.
A T? distinguishes a real value from no value without relying on special sentinel data. The compiler requires callers to handle both cases, which prevents accidental use of missing data and makes API contracts clearer.
Possible follow-ups
Learning stage
Optionals are not errors or empty containers; they are types that express possible absence. Handle that absence at a meaningful boundary and keep the rest of the code non-optional when possible.