Optionals
Prerequisites: Data types and type inference
Sometimes a value might be missing: a user may not have entered a middle name, a search may find nothing, text may not be a valid number. Swift represents "a value, or nothing" with an optional. Optionals are the single most important idea that makes Swift safe.
Real-world analogy: an optional is a gift box that might be empty. Before you use the gift, you have to open the box and check.
Syntax
Add ? to a type to make it optional. "Nothing" is written nil:
var middleName: String? = nil
var nickname: String? = "Addy"
Where optionals come from
Many operations return an optional because they can fail:
let good = Int("42") // Int? containing 42
let bad = Int("forty") // Int? containing nil
print(bad == nil)
print(good == 42)
true
true
Array properties such as first and last are optionals too — the
array might be empty.
You can't use an optional directly
A String? is not a String. Swift won't let you use it as one
until you check it isn't nil:
let nickname: String? = "Addy"
print(nickname.count)
error: value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'
That error is Swift protecting you. In many languages, forgetting this check crashes the program with a "null reference" error — often in front of a user. Swift makes you handle the missing case before the code even compiles.
Getting the value out safely is called unwrapping, and it's the subject of the next lesson.
Common mistakes
- Printing an optional directly.
print(nickname)showsOptional("Addy")and the compiler warns about it. Unwrap it first. - Making everything optional "just in case". Only use
?when a value can genuinely be missing — every optional adds checks for the reader.