Skip to content

/errors/swift/unexpectedly-found-nil-while-unwrapping

Swift Fatal error: Unexpectedly found nil while unwrapping an Optional value

The commands on this page have not been executed by our verification runner yet.updated
tool
Swift
versions
Swift 5.x – 6.x
os
macos, linux, windows

Fatal error: Unexpectedly found nil while unwrapping an Optional value is a Swift run-time crash: the code used ! to force-unwrap an Optional that held nil. Swift stops the program instead of continuing with a missing value. Find the ! on the line in the crash report and replace it with if let, guard let or ?? so the nil case is handled. A variant, ... while implicitly unwrapping an Optional value, comes from implicitly unwrapped optionals (Type!), most often an @IBOutlet that is not connected.

Example

swift
let input = "abc"
let port = Int(input)!   // Int("abc") is nil: fatal error at run time
print(port)

Int(_:) is a failable initializer and returns Int?. The ! asserts that it is not nil; when the assertion is wrong, the program traps.

Fixes

swift
// 1. Optional binding
if let port = Int(input) {
    print("port \(port)")
} else {
    print("invalid port: \(input)")
}

// 2. Early exit
guard let port = Int(input) else {
    throw ConfigError.invalidPort(input)
}

// 3. Default value
let port = Int(input) ?? 8080

// 4. Optional chaining: the result is nil instead of a crash
let length = user?.name?.count

Implicitly unwrapped optionals and outlets

@IBOutlet weak var label: UILabel! is an implicitly unwrapped optional: using it reads like a normal value but unwraps it every time. If the outlet is not connected in the storyboard, or the view controller is created with init() instead of from the storyboard, the outlet is nil and the first use crashes with the implicit variant of the message.

Sources