How to use Timer (NSTimer) in Swift: creating, stopping and repeating a timer
Hi! I just started learning Swift and am trying to implement a simple countdown timer in my app. I need the value on the screen to update every second, and the timer to stop after 10 seconds.
I found the Timer class in the documentation, but I'm having issues. Here's what I'm trying to do:
```swift
var seconds = 10
func startTimer() {
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
seconds -= 1
print(seconds)
if seconds == 0 {
// How to stop the timer?
}
}
```
The timer starts and counts down the seconds, but I don't understand:
1. How to properly stop the timer when `seconds` becomes 0?
2. Why does Xcode sometimes give a pr
No answers yet.
Log in to leave an answer
Blogs