swift属性观察器_在Swift中什么是财产观察员?

swift属性观察器

In this article, we will learn what are property observers in Swift and how to use them effectively.

在本文中,我们将学习什么是Swift中的属性观察器以及如何有效地使用它们。

We will do so quickly experimenting with them in an Xcode Playground.

我们将很快在Xcode Playground中对它们进行试验。

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

源代码位于文章底部。

开始吧 (Let’s Start)

We have two types of property observers:

我们有两种类型的属性观察器:

  • willSet — called before a new value is stored

    willSet — 存储新值之前调用

  • didSet — called after a new value is stored

    didSet — 存储新值之后调用

Let’s create a simple message variable:

让我们创建一个简单的message变量:

And assign a new value to it:

并为其分配一个新值:

Now we have the following printed in the console:

现在,我们在控制台中打印了以下内容:

Image for post

As we can see, the willSet gets executed before the didSet. So at the time willSet is run, we can obtain a new value that is being assigned to the variable. However, the value is not stored yet in the property.

如我们所见, willSetdidSet之前执行。 所以在当时willSet运行时,我们可以获取分配给新的变量值。 但是,该值尚未存储在属性中。

Once didSet is executed, the new value is stored. This is why we have a newValue parameter in willSet and an oldValue in didSet.

执行didSet ,将存储新值。 这就是为什么我们在willSet有一个newValue参数,在willSet一个oldValuedidSet

We can also change the name of the willSet parameter as follows:

我们还可以如下更改willSet参数的名称:

Let’s now consider a practical example.

现在让我们考虑一个实际的例子。

Say we have a simple UIView called CustomView:

假设我们有一个名为CustomView的简单UIView

Let’s change the message property as follows:

让我们如下更改message属性:

And assign to it a new value three seconds after the CustomView is initialized:

并在CustomView初始化三秒钟后为其分配一个新值:

Now if we run the Playground, the willSet property observer triggers the UI update in three seconds:

现在,如果我们运行Playground,则willSet属性观察器将在三秒钟内触发UI更新:

Image for post

资源资源 (Resources)

The source code is available in a Gist.

源代码在Gist中可用。

结语 (Wrapping Up)

Interested in more lesser-known features of Swift? Feel free to check out my other relevant articles:

对Swift鲜为人知的功能感兴趣吗? 随时查看我的其他相关文章:

Thanks for reading!

谢谢阅读!

翻译自: https://levelup.gitconnected.com/what-are-property-observers-in-swift-4bda0945973

swift属性观察器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值