How do you fix "Unexpectedly found nil while unwrapping an Optional value"?

← Swift answers

Something marked with ! (or an implicitly unwrapped IBOutlet) was nil at runtime. Replace the force unwrap with if let, guard let or a default value.

let text = field.text          // String?
 
let a = text!                  // crashes if nil
 
if let a = text { print(a) }   // run only when present
 
guard let b = text else { return }   // exit early
print(b)
 
let c = text ?? ""             // default value
  • IBOutlets: a nil outlet usually means the connection in Interface Builder is broken or the property is used before viewDidLoad. Check for a yellow warning or an empty circle next to the outlet.
  • Failable initializers and lookups such as URL(string:), Int("abc") or dictionary subscripts return optionals; handle the nil case.
  • try! and as! crash the same way; prefer try?, do/catch and as?.
When this crash happens on a user's device, Bugsee shows the symbolicated stack trace, the screen and the steps before it. Learn more

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required