variable "mysteriously" cleared after set within clicked event

55 Views Asked by At

I am doing the uDemy training on Swift and I was trying to enhance a timer application by reading in a timer value from a text box (secondsText). My variable, "counter" gets set by reading in the value of secondsText, but then by the time I exit the startClicked function, the "counter" value is 0.

class ViewController: UIViewController {
    var counter = 0
    var timer = Timer()

    @IBOutlet weak var labelText: UILabel!
    @IBOutlet weak var secondsText: UITextField!


   @objc func timerFunction() {

      print("timerFunction: \(counter)")
      if(counter == 0) {
          timer.invalidate()
          labelText.text = "Timer Complete"
      } else
          counter = counter - 1
          print("timerFunction: \(counter)")
          labelText.text = "Time: \(counter)"
      }
   }

   @IBAction func startClicked(_ sender: Any) {
      if let counter = Int(secondsText.text) {
          print("Timer = \(counter)")
          labelText.text = "Time: \(counter)"
          print("startClicked.Timer 1: \(counter)")
          timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)

          print("startClicked.Timer 2: \(counter)")

      } else {
           print("Invalid timer value")
           labelText.text = "Time: \(counter)"
      }
      print("startClicked.Timer 3: \(counter)")
   }
}
1

There are 1 best solutions below

1
Lou Franco On

The counter on the line

 if let counter = …

Is hiding the member variable counter inside the if. You should use a different name.

And then assign self.counter to that value if you want to save it.