EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I got this when I run my app "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)". See the code:

@IBAction func signUpAction(_ sender: Any) {
      
        let email = emailTextField.text!.lowercased()
        let finalEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
    
        let username = usernameTextField.text!
        let password = passwordTextField.text!
        let firstLastName = firstLastNameTextField.text!
        let pictureData = UIImageJPEGRepresentation(self.userImageView.image!, 0.7)// Here
     

I cannot delete ! because if I do so I will get an error. For more info, this is my logs "fatal error: unexpectedly found nil while unwrapping an Optional value". Do anyone knows how to fix it? Please help me. Thanks.

More updates, I got this logs at the left hand side: "pictureData = (Data?) nil"

Do you have an image in the imageView? Based on your follow-up, it doesn't appear that you do.


You need to validate the data is there, by using the self.userImageView.image! you are force unwrapping the value. This is useful in the case where you know the data is there, but in this case it appears you don't have the data so you're attempting to force unwrap nil and passing it into the UIImageJPEGRepresentation constructor. You can't do that, which is why you're receiving the EXC_BAD_INSTRUCTION exception.

So, I have to add an image into the image view?

If you are force unwrapping the object (using !) then yes. You should be validating that the object exists before force unwrapping a value. Ideally you would not be force unwrapping the value, because it would be unwrapped from your validation.


In the case that you're describing with the snippet above, you'd probably want to do something like this:

// This will attempt to create pictureData using the UIImageJPEGRepresentation constructor as identified.
// If it's successful, it will pass the pictureData into the if block, otherwise it will fail and go to else.
if let pictureData = UIImageJPEGRepresentation(self.imageView.image!, 0.7) {
     // Do something with the picture data.
} else {
     // Show an error or something related to the image being missing.
}


The main point to take away from this is that when unwrapping Optional values (ones that have ? in the typing), you cannot unwrap a nil value. Because of this, you need to validate that there is data in the value prior to unwrapping it.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
 
 
Q