Swift Optionals
Handle values that might be missing with if let.
Swift
let values = ["42", "x7"]
for text in values {
if let number = Int(text) {
print("number \(number + 1)")
} else {
print("not a number: \(text)")
}
}Output
number 43 not a number: x7
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
let values = ["42", "x7"]2
for text in values {3
if let number = Int(text) {4
print("number \(number + 1)")5
} else {6
print("not a number: \(text)")7
}8
}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 |
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.