c++ combine使用_使用Combine编写更多可读的Swift代码

c++ combine使用

In this article, we will learn how to make our Swift code more distinctive and efficient by using Combine.

在本文中,我们将学习如何通过使用Combine使我们的Swift代码更具特色和效率。

Without further ado, let’s get started.

事不宜迟,让我们开始吧。

开始吧 (Let’s Start)

If you ever needed to observe for keyboard events, then this code probably looks very familiar:

如果您需要观察键盘事件,那么此代码可能看起来非常熟悉:

Once we receive the keyboardWillShowNotification, we simply print a message in the console. By using Combine, we can make the code more succinct without needing to pass those nil values as parameters:

一旦收到keyboardWillShowNotification ,我们只需在控制台中打印一条消息。 通过使用Combine,我们可以使代码更加简洁,而无需将这些nil值作为参数传递:

To write an asynchronous logic, you would usually include an escaping closure as a parameter:

要编写异步逻辑,通常将转义的闭包作为参数包括在内:

You can use the Combine’s future instead:

您可以改为使用合并的未来:

With this approach, you would be able to use a variety of Combine operators to transform or filter your data. Moreover, you could use the .assign operator to bind the result to a property.

使用这种方法,您将能够使用各种组合运算符来转换或过滤数据。 此外,您可以使用.assign运算符将结果绑定到属性。

Before Combine, you would write something like this to create a simple repeating timer:

在合并之前,您将编写如下代码来创建一个简单的重复计时器:

With a Combine publisher, you make it look better:

使用Combine发行商,您可以使它看起来更好:

As a result, we see each second printed in the console:

结果,我们看到每秒在控制台中打印:

Image for post

When following the MVVM design pattern, you would create closure properties to be invoked every time a given asynchronous event occurs:

当遵循MVVM设计模式时,您将创建每次给定异步事件发生时都会调用的闭包属性:

Let’s use Combine’s PassthroughSubject instead:

让我们改用Combine的PassthroughSubject

We see that after three seconds, a message is printed:

我们看到三秒钟后,将显示一条消息:

Image for post

翻译自: https://medium.com/better-programming/use-combine-to-write-more-readable-swift-code-9e8e6cf0bf50

c++ combine使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值