0

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
        }
    }
}
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • 1
    `eggTimes[hardness]!` will crash when `hardness` isn't one of the available keys in the dictionary. Try to avoid force-unwrapping as much as you can. – Gereon Dec 14 '20 at 16:21
  • If I don't force-unwrap it I get an error message on secondsRemaining = eggTimes[hardness]! stating that the optional type needs to be unwrapped. What would be the best way to call from the dictionary when either button is pressed? – Matthew Jackson Dec 14 '20 at 16:31

1 Answers1

1

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
}
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • Thread 1: "-[EggTimer.ViewController startTimer:]: unrecognized selector sent to instance 0x7fc4da4090d0" This is the error I now receive on my class ViewController: UIViewController I never call for eggTimer. I use eggTimes in a dict. To start the timer I use an objc func and call for timer within my IBAction. Is eggTimer the "unrecognized selector"? – Matthew Jackson Dec 14 '20 at 17:05
  • No `startTimer` is to blame. However, this seems like an entirely different question. – Gereon Dec 14 '20 at 18:26