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)")
}
}
The
counteron the lineIs hiding the member variable
counterinside theif. You should use a different name.And then assign
self.counterto that value if you want to save it.