What is causing a "EXC_Bad_Instruction" error in this code?

101 Views Asked by At

From my understanding, the error is coming from something being set to "nil". The only thing set to "nil" in my code is the userInfo which should be "nil" since there will never be any data there. Any help is appreciated!

import UIKit
    
class ViewController: UIViewController {
    let eggTimes = [
        "soft": 300, "medium" : 420, "hard" : 720 ]
    
    var secondsRemaining = 60
    
    var timer = Timer()
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
       
        timer.invalidate()
        
        let hardness = sender.currentTitle!
        
        secondsRemaining = eggTimes[hardness]!
    
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
        
    @objc func updateTimer() {
        //example functionality
        if secondsRemaining > 0 {
            print("\(secondsRemaining) seconds to the end of the world")
            secondsRemaining -= 1
        }
    }
}
1

There are 1 best solutions below

2
Gereon On

This line

secondsRemaining = eggTimes[hardness]!

is the likely culprit, replace it with something like

guard let secondsRemaining = eggTimes[hardness] else {
    // `hardness` isn't a valid key
    print("unknown key: \(hardness)")
    return
}