swift计时器
In this tutorial we will learn how to create a simple repeating timer using a built-in Combine’s publisher.
在本教程中,我们将学习如何使用内置的Combine的发布者创建简单的重复计时器。
We will do so by quickly implementing it in an Xcode Playground.
我们将通过在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:
首先,我们需要创建一个AnyCancellable
Set
, AnyCancellable
存储计时器订阅:
Now let’s specify the starting Date
we will use for our timer:
现在,让我们指定将用于计时器的开始Date
:
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):
我们可以通过在Foundation的Timer
类上使用.publish
方法来创建计时器(我们将值1.0指定为参数,因为我们想每秒打印一个值):
The .autoconnect()
allows us to start a timer once we have a subscriber. If we don’t use that operator, then we will need to call .connect()
manually.
.autoconnect()
允许我们在有订阅者后启动计时器。 如果不使用该运算符,则需要手动调用.connect()
。
Let’s now obtain the TimeInterval
and transform it into an Int
using the .map
operator:
现在,我们获取TimeInterval
并使用.map
运算符将其转换为Int
:
All that is left is to subscribe for the publisher and store the resulting subscription in our previously defined Set
of AnyCancellable
s:
所有剩下的认购发行所得订阅存储在我们先前定义Set
的AnyCancellable
S:
As a result, we have the seconds printed out:
结果,我们打印出了几秒钟:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/4f4c930767fd3e64d5262ccbcb2d6602.png)
资源资源 (Resources)
The source code is available in a Gist.
源代码在Gist中可用。
结语 (Wrapping Up)
Interested in more Swift articles? Feel free to visit my other relevant pieces:
对更多Swift文章感兴趣吗? 随时访问我的其他相关文章:
Thanks for reading!
谢谢阅读!
翻译自: https://medium.com/cleansoftware/swift-how-to-create-a-timer-in-combine-43192dab4d3
swift计时器