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.