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:
现在,我们在控制台中打印了以下内容:
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.
如我们所见, willSet
在didSet
之前执行。 所以在当时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
一个oldValue
的didSet
。
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更新:
资源资源 (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属性观察器