Swift Optionals
Handle values that might be missing with if let.
On this page
Swift conditionals and loops.
- Handle values that might be missing with if let.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
An optional type, written Int?, either holds a value or holds nil. Int("42") returns an Int? because the text may not be a number. Swift forces you to deal with the possibility of nil before using the value.
if let number = Int(text) tries the conversion and, only if it succeeds, binds the unwrapped Int to number for the first block. Otherwise the else block runs.
Code example
let values = ["42", "x7"]
for text in values {
if let number = Int(text) {
print("number \(number + 1)")
} else {
print("not a number: \(text)")
}
}number 43 not a number: x7
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
let values = ["42", "x7"]for text in values { if let number = Int(text) { print("number \(number + 1)") } else { print("not a number: \(text)") }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Two strings, only one of which is a number. | — | — | |
| For "42" the conversion succeeds and number is 42. | text = "42", number = 42 | — | |
| Print the number plus one. | text = "42", number = 42 | number 43 | |
| For "x7" the conversion gives nil, so the else block runs. | text = "x7" | number 43 not a number: x7 |
Behind the scenes
How Swift processes this code
Swift compiles the program; its top-level statements run in source order.
Cost and common mistakes
O(n) over the values; each conversion is linear in the text length.
- Force unwrapping with ! crashes when the value is nil; prefer if let, guard let, or ??.
- Int(" 42") with a space also returns nil; the text must be exactly a number.
Try it yourself
Give failed conversions a default of 0.
Reveal answer and reasoning
Use let number = Int(text) ?? 0 and print number + 1 for every entry.