what does Error “Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)” mean?

后端 未结 10 1060
情歌与酒
情歌与酒 2020-11-29 02:42

I got this error:

Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

How can I solve this? The code works normally,

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:09

    Your secondNumber seems to be an ivar, so you have to use a local var to unwrap the optional. And careful. You don't test secondNumber for 0, which can lead into a division by zero. Technically you need another case to handle an impossible operation. For instance checkin if the number is 0 and do nothing in that case would at least not crash.

    @IBAction func equals(sender: AnyObject) {
    
        guard let number = Screen.text?.toInt(), number > 0 else {
            return
        }
    
        secondNumber = number
    
        if operation == "+"{
            result = firstNumber + secondNumber
        }
        else if operation == "-" {
            result = firstNumber - secondNumber
        }
        else if operation == "x" {
            result = firstNumber * secondNumber
        }
        else {
            result = firstNumber / secondNumber
        }
        Screen.text = "\(result)"
    }
    

提交回复
热议问题