Search code examples
iosswifttimeruikit

Unexpected Output: I am using the below code to print out the timer according to the button pressed but timer is starting with 20 only. what's wrong?


import UIKit

class ViewController: UIViewController {
    let eggTimes =  ["Soft": 60,"Medium": 72,"Hard": 95]
    
    var secondsRemaining = 20
    
    var timer = Timer()
     
    
    @IBAction func hardnessSelected(_ sender: UIButton) {
         
        let hardness = sender.currentTitle!
        
        var secondsRemaining = eggTimes[hardness]!

        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
       
    }

    @objc func timerAction()
    {
        if secondsRemaining > 0 {
            print("\(secondsRemaining) seconds")
            secondsRemaining -= 1
        }
    }
}

Unexpected Output: I am using the below code to print out the timer according to the button pressed but timer is starting with 20 only. what's wrong?


Solution

  • You are creating a new variable inside your Button function:

    var secondsRemaining = eggTimes[hardness]!
    

    instead you should assing your value. It should be:

    self.secondsRemaining = eggTimes[hardness]!