Abdalla AlHaj Hasan Abdalla AlHaj Hasan - 3 months ago 7x
Swift Question

how to fix EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0) in swift

Am making image library that make me abel to select multiple image from the collection view that i made
When i fun my code averting is good ,but when i press select button this error happen "EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)"

this is the select button code

@IBAction func Select(sender: AnyObject) {
var ckeck = AssetCell() as? AssetCell
ckeck!.CheckMarkView1.hidden = false // here it shows an error which is "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

i had Assetcell class that contain CheckMarkView1


When you say AssetCell() as? AssetCell it means that your ckeck is an Optional, which again means that it can be something or it can be nil (nothing).

When you in the next line say ckeck!, that means that you are telling the compiler to just handle the value of ckeck and you don't care whether it is nil or not. This is almost always a bad idea as you have just found out the hard way.

A better way is to use either if let syntax to unwrap or guard syntax.

So you could say:

if let ckeck = ckeck {
    ckeck!.CheckMarkView1.hidden = false

Or you could say:

guard let ckeck = ckeck else { return }
ckeck!.CheckMarkView1.hidden = false

That way you are sure to only start using ckeck if it actually has a value.

Having said that, the way you actually create ckeck looks a bit odd:

var ckeck = AssetCell() as? AssetCell

Now I don't know the details, but couldn't you just say

let ckeck = AssetCell()

And finally...this question has been asked a great many times already in various forms. I know that it is frustrating when you have an error and you don't quite understand what is going on, but the next time you should start with a search for EXC_BAD_INSTRUCTION for instance. This should return a lot of answers to help you solve the problem, or at least help you get a clue about what is happening. Sorry :)