Last active
July 17, 2023 20:45
-
-
Save dreymonde/7538c4ac708bafc6d2e743a14ceedd4a to your computer and use it in GitHub Desktop.
"Timers" helper class for Swift with automatic memory management and intuitive API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Timers { | |
private var timers: [Foundation.Timer] = [] | |
public init() { } | |
public func clear() { | |
for timer in timers { | |
timer.invalidate() | |
} | |
timers = [] | |
} | |
deinit { | |
clear() | |
} | |
internal func addTimerManually( | |
runLoop: RunLoop = .main, | |
runLoopMode: RunLoop.Mode = .common, | |
timer: Timer | |
) { | |
runLoop.add(timer, forMode: runLoopMode) | |
timers.append(timer) | |
} | |
public func addRepeating<TargetType: AnyObject>( | |
timeInterval: TimeInterval, | |
tolerance: TimeInterval = 0, | |
withTarget target: TargetType, | |
handler: @escaping (TargetType, Timer) -> Void | |
) { | |
let newTimer = Timer(timeInterval: timeInterval, repeats: true) { [weak target] timer in | |
if let target { | |
handler(target, timer) | |
} | |
} | |
newTimer.tolerance = tolerance | |
addTimerManually(timer: newTimer) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment