Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count Timer on Swift

Tags:

swift

timer

I'm a newbie in swift and I tried to make a Timer. It should normally count the seconds and print them in the debugger.

I tried this:

var timer = Timer() 

@IBAction func killTimer(_ sender: AnyObject) {
    timer.invalidate()         
}

@objc func processTimer() {
    print("This is a second")
}

override func viewDidLoad() {
    super.viewDidLoad()

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

I don't know how the timer count seconds.. With this code i get an fail message:

@objc func processTimer() {
    print("This is second \(Timer + 1)")
}

Thanks for your help. A

like image 932
Iskandir Avatar asked Oct 16 '25 15:10

Iskandir


1 Answers

You need a counter variable which is incremented every time the timer fires.

Declare the variable Timer as optional to invalidate the timer reliably (only once).

var timer : Timer?
var counter = 0 

@IBAction func killTimer(_ sender: AnyObject) {
   timer?.invalidate()
   timer = nil
}

@objc func prozessTimer() {
    counter += 1
    print("This is a second ", counter)

}

override func viewDidLoad() {
    super.viewDidLoad()  
    timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(prozessTimer), userInfo: nil, repeats: true)

}
like image 152
vadian Avatar answered Oct 18 '25 09:10

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!