Optionals
A TrailLog hike may or may not have a note, a photo, or a finish time. In many languages "no value" hides as null inside any variable, waiting to crash. Swift puts the possibility of absence into the type itself, so you cannot forget it.
The rule
A
?type is a box that may be empty — open it before use.
String? means "a String, or nothing". Nothing is written nil. A plain String can never be nil.
var note: String? = nil
note = "Muddy after the rain"You cannot use note as a String directly; you must unwrap it first. Four tools, from safest to riskiest:
// 1. if let — run a block only when there is a value
if let note {
print("Note: \(note)")
}
// 2. guard let — leave early when there is no value
func showPhoto(_ photo: UIImage?) {
guard let photo else { return }
imageView.image = photo // photo is unwrapped from here on
}
// 3. ?? — supply a default
let shown = note ?? "No note"
// 4. ! — force unwrap: crashes if nil
let risky = note!There is also optional chaining with ?.: hike.photo?.size returns an optional size, or nil if there is no photo, without crashing.
Many everyday APIs return optionals because they can fail: Int("12") gives 12, but Int("twelve") gives nil, so its type is Int?. Dictionary lookups return optionals too, because the key may be missing.
The shortcut
When you meet an optional, pick the tool by asking "What should happen when it is empty?"
- Skip some work →
if let - Stop the whole function →
guard let - Use a fallback value →
?? - It truly cannot be empty and a crash is the right signal →
!(rare)
The value
hike.finishedAtisDate?because an ongoing hike has not finished.
The trap is reaching for ! to silence the compiler. Every ! is a promise that the value is never nil; when that promise breaks, the app crashes in front of the user.
Drills
Answer fast — trust the rule.
What is the type of Int("twelve")?
note is nil. What is note ?? "No note"?
A function cannot do anything useful without a user ID that might be missing. Which tool fits best?
hike.photo is nil. What does hike.photo?.size produce?
Which line crashes when note is nil?
Remember
- A
?type may be empty (nil); unwrap it before use. - Choose by the empty case: skip →
if let, stop →guard let, default →??. - Trap:
!is a crash waiting for the one time the value is missing.
