Member-only story
What is “Fatal error: Unexpectedly found nil while unwrapping an Optional value”?
2 min readJan 14, 2020
A swift variable can be any of the following types:
var anVar: Int = 10
var anOptionalVar: Int? = 42
var anNonOptionVar: Int! //Have no valid value, this value is implicitly unwrapped, usually used in dependecy injection
var anUninitializedOptionalVar: Int? // `nil` is the default
An optional variable is a type that represents either a wrapped value or nil
, the absence of a value.
To access a value for an option variable, you have to unwrap it. There are five ways to unwrap an optional.
Nil Cascading operator:
This is one of the safest ways to access Option. This usually never crashes:
var anOptionalVar: Int? = 42if let nonOptionalVar = anOptionalVar {
print("\(nonOptionalVar)")
} else {
print("nonOptionalVar is nil")
}
Optional Chaining:
To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (postfix ?
). This usually never crashes:
class Student {
let name: String?
let address: String? }var student: Student?if student?.name == nil {
print("not a valid name")
}
Forced unwrapping: