Swift: How to Create a Timer in Combine

Using a built-in publisher

Zafar Ivaev
Clean Software

--

Photo by Tyler Franta on Unsplash

In this tutorial we will learn how to create a simple repeating timer using a built-in Combine’s publisher.

We will do so by quickly implementing it in an Xcode Playground.

The full source code is available at the bottom of the article.

Let’s Start

First we need to create a Set of AnyCancellable where we will store our timer subscription:

Now let’s specify the starting Date we will use for our timer:

We can create a timer by using the .publish method on the Foundation’s Timer class (we specify the value of 1.0 as a parameter, because we want to print a value every second):

--

--

Zafar Ivaev
Clean Software

Senior iOS Engineer. I write about features of Swift and iOS development practices.