#46: Unexpectedly Found nil While Unwrapping an Optional

That error appears when code force-unwraps an optional with !, but the value is actually nil at runtime.

let text: String? = nil
print(text!) // crash

The fix is usually to unwrap safely:

if let text {
    print(text)
} else {
    print("Missing value")
}

You can also use guard let, optional chaining, or the nil-coalescing operator:

let name = text ?? "Anonymous"

Force unwrapping is only appropriate when nil is truly impossible and you are willing to treat violations as programmer errors.


I'm also on Twitter and GitHub.

Subscribe via RSS.