Swift Optionals
In many languages any variable can secretly be null, and forgetting to check for it is one of the most common causes of crashes. Swift solves this with optionals: a value that might be missing has a different type than a value that is always there.
| Type | Can hold |
|---|---|
String |
always a string |
String? |
either a string or nil (no value) |
The compiler won't let you use a String? where a String is expected until you have dealt with the nil case.
Declaring optionals
Add ? after a type. An optional variable without an initial value starts as nil:
var middleName: String? = nil
var nickname: String? // also nil
let age: Int? = 42
print(middleName as Any)
print(nickname as Any)
print(age as Any)
middleName = "Grace"
print(middleName as Any)nil
nil
Optional(42)
Optional("Grace")
Printing an optional shows the wrapper Optional(…). (as Any just silences a compiler warning about printing optionals.)
Many standard functions return optionals because they can fail — converting text to a number, for example:
let good = Int("123")
let bad = Int("12abc")
print(good as Any)
print(bad as Any)Optional(123)
nil
You can't use an optional directly
let input: String? = "hello"
print(input.uppercased())error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:2:7: error: value of optional type 'String?' must be unwrapped to refer to member 'uppercased' of wrapped base type 'String'
1 | let input: String? = "hello"
2 | print(input.uppercased())
| |- error: value of optional type 'String?' must be unwrapped to refer to member 'uppercased' of wrapped base type 'String'
| |- note: chain the optional using '?' to access member 'uppercased' only for non-'nil' base values
| `- note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
There are several ways to unwrap an optional safely.
if let — optional binding
if let checks for a value and, if there is one, gives you a non-optional constant inside the braces. Since Swift 5.7 you can write the short form if let name instead of if let name = name:
let username: String? = "swiftie42"
let email: String? = nil
if let username {
print("Logged in as \(username.uppercased())")
}
if let address = email {
print("Email: \(address)")
} else {
print("No email on file")
}
// Several bindings and conditions at once
let widthText = "8", heightText = "5"
if let w = Int(widthText), let h = Int(heightText), w > 0 {
print("Area: \(w * h)")
}Logged in as SWIFTIE42
No email on file
Area: 40
guard let — early exit
guard let is the mirror image: if the value is missing you must leave the current scope (return, break, continue or throw). After the guard, the unwrapped value is available for the rest of the function — no extra nesting:
func greet(_ name: String?) {
guard let name, !name.isEmpty else {
print("Hello, stranger!")
return
}
print("Hello, \(name)!")
}
greet("Noor")
greet(nil)
greet("")Hello, Noor!
Hello, stranger!
Hello, stranger!
Tip: Use
guardto check preconditions at the top of a function, andif letwhen you only need the value in a small block.
Nil-coalescing operator ??
a ?? b returns the value inside a, or b if a is nil. It's the quickest way to supply a default:
let savedVolume: Int? = nil
let volume = savedVolume ?? 50
print("Volume: \(volume)")
let quantity = Int("seven") ?? 0
print("Quantity: \(quantity)")
let theme: String? = "dark"
print("Theme: \(theme ?? "light")")Volume: 50
Quantity: 0
Theme: dark
Optional chaining ?.
Write ?. to call a property or method only if the value exists. If anything in the chain is nil, the whole expression becomes nil — and the result is always optional:
let words: [String] = ["swift", "rocks"]
let noWords: [String] = []
print(words.first?.uppercased() as Any)
print(noWords.first?.uppercased() as Any)
print(words.first?.count ?? 0)
print(noWords.last?.count ?? 0)Optional("SWIFT")
nil
5
0
Force unwrapping !
Writing ! after an optional says "I am sure there is a value — just give it to me". If you're wrong, the program crashes:
let number: Int? = nil
print(number!) // 💥 Fatal error: Unexpectedly found nil while unwrapping an Optional valueOnly force-unwrap when a nil would be a programming error, for example Int("42")! with a literal you control. In all other cases prefer if let, guard let or ??.
Summary
| Technique | Syntax | When |
|---|---|---|
| Optional binding | if let x { … } |
use the value in a block |
| Early exit | guard let x else { return } |
value is required for the rest of the function |
| Default value | x ?? fallback |
a sensible fallback exists |
| Optional chaining | x?.property |
call through something that may be missing |
| Force unwrap | x! |
you can prove it isn't nil |
Test yourself
What is the value of Int("abc")?
- 0
- nil
- A crash
- "abc"
What does let n: Int? = nil; print(n ?? 7) print?
- nil
- Optional(7)
- 7
- 0
In a guard let x = maybe else { … } statement, what must the else block do?
- Print an error
- Exit the current scope (return, break, continue or throw)
- Assign a default value to x
- Nothing special