Timers in Swift
In Swift, we use the Timer
class to create timers. Here’s a breakdown of the translation:
We import Foundation
instead of specific packages, as it includes the necessary timing functions.
The time.NewTimer
is replaced with Timer.scheduledTimer
, which takes a time interval and a closure to execute when the timer fires.
Instead of using channels to wait for the timer, we use RunLoop.current.run(until:)
to block the current thread until the timer fires.
The go
keyword for creating a goroutine is replaced with DispatchQueue.global().async
, which runs the given closure asynchronously.
Instead of timer2.Stop()
, we use timer2.invalidate()
to stop the timer.
We check if the timer is stopped by checking !timer2.isValid
instead of the return value of the stop function.
time.Sleep
is replaced with Thread.sleep(forTimeInterval:)
.
To run this program, save it as Timers.swift
and use the Swift compiler:
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.