Chapter 12: Unexpectedly found nil while implicitly unwrapping

After adding this line to AddItemViewController:
textField.becomeFirstResponder()

I get this:

Unexpectedly found nil while implicitly unwrapping

Help!

Hi @steveb_la, the error “unexpectedly found nil while implicitly unwrapping” will usually point to an optional’s value being nil. You can unwrap it safely using a guard statement for example or forcibly. In this case, if you are using a storyboard the IBOutlet connected to the textField, I would make sure it is properly named and connected.

Best,
Gina

Hi @gdelarosa ,

I was looking for example guard statements. Could you point me to some?

Thank you.

Steve

Sure thing @steveb_la,

One example here displays the parameter firstName as an optional. Then using a guard let statement we can make sure firstName is not nil.

func checkIn(_ firstName: String?) {
    guard let unwrapName = firstName else {
        print("Not a valid name in our system.")
        return
    }

    print("Thank you for checking in \(unwrapName)!")
}

Resources:

Best,
Gina

Thank you for those references. I’ll go look at them. I was playing around and found that this works. (Xcode 12.4)
textField?.becomeFirstResponder()

@steveb_la Please check out my tutorial about guard statements when you get a chance:

I hope it helps!