Member-only story
Implementing A Simple Timer Wrapper In Swift
Improve coding process by implementing simple and practical solutions
It becomes quite often necessary when implementing apps to create tasks that are either being repeated at a constant interval, or they are executed after a certain period of time. For instance, we might want to display a message for a few seconds and then make it disappear, or to save user-edited text periodically. In order to serve such purposes, the Foundation framework provides us with a handy class to use, the well known Timer.
Quite probably, you are already familiar with Timer, one way or another. In SwiftUI, we mostly use its more suitable Combine-related APIs, while in UIKit or AppKit we usually schedule an instance of it using specific static methods. Admittedly, it’s not difficult to work with Timer when coding. But even the few steps of preparation might feel sometimes as an extra hassle that we’d like to avoid, especially when there’s a pile of other tasks to implement or fix. So, in this post I’ll show how to create a simple wrapper that will make it easier to start and stop a timer in Swift.
The custom timer type
We’ll start the implementation of the timer wrapper by defining a new custom type; a class in particular, which we’ll name HandyTimer
-😉-: