Swift optionals and nil
By Flavio
Published · Updated
Tagged: Swift
Learn how optionals and nil work in Swift, how to declare an optional with a question mark, and how to safely unwrap its value using an if let statement.
This tutorial belongs to the Swift series
Optionals are one key feature of Swift.
When you don’t know if a value will be present or absent, you declare the type as an optional.
The optional wraps another value, with its own type. Or maybe not.
We declare an optional adding a question mark after its type, like this:
var value: Int? = 10
Now value is not an Int value. It’s an optional wrapping an Int value.
Unwrapping
To find out if the optional wraps a value, you must unwrap it.
! is force unwrapping: it crashes at runtime if the optional is nil. Use it only when you’re sure there’s a value. To check safely, compare with nil or use optional binding (if let, guard let), or give a fallback with ?? (for example value ?? 0).
var value: Int? = 10
print(value!) //10
This is the crash you get if you force unwrap an empty optional: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
Swift methods often return an optional. For example the Int type initializer accepts a string, and returns an Int optional:

This is because it does not know if the string can be converted to a number. Int("37") gives you Optional(37). Int("test") gives you nothing.
nil
If the optional does not contain a value, it evaluates as nil, and you cannot unwrap it:

nil is a special value that cannot be assigned to a non-optional variable. Only to an optional:


That’s the point. A plain Int is a promise the value is always there. You never have to check it.
Unwrapping safely with if let
You typically use if statements to unwrap values in your code, like this:
var value: Int? = 2
if let age = value {
print(age)
}
If value contains something, Swift puts it in the new constant age and runs the block. age is a plain Int, not an optional. If value is nil, the block is skipped. No crash.
Since Swift 5.7 you can write if let value { instead of if let value = value {:
var value: Int? = 2
if let value {
print(value)
}
My advice: treat ! as a warning sign. Ask what should happen when the value is missing, and write an if let instead.
If a default value makes sense, ?? gives it to you in one line:
let age = Int("test") ?? 0 // 0
?? is the nil-coalescing operator. It returns the value inside the optional if there is one, or the fallback on the right if there isn’t.
Want me to talk about your product? You can sponsor this site.
Related posts about swift: