Swift 中 willSet 和 didSet 的目的是什么? [英] What is the purpose of willSet and didSet in Swift?

查看:23
本文介绍了Swift 中 willSet 和 didSet 的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 的属性声明语法与 C# 非常相似:

Swift has a property declaration syntax very similar to C#'s:

var foo: Int {
    get { return getFoo() }
    set { setFoo(newValue) }
}

然而,它也有 willSetdidSet 动作.它们分别在调用 setter 之前和之后调用.考虑到您可以在 setter 中使用相同的代码,它们的目的是什么?

However, it also has willSet and didSet actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?

推荐答案

重点似乎是有时,您需要一个具有自动存储功能的属性一些行为,例如通知其他对象属性刚刚改变.当您只有 get/set 时,您需要另一个字段来保存值.使用 willSetdidSet,您可以在修改值时采取行动,而无需其他字段.例如,在那个例子中:

The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified without needing another field. For instance, in that example:

class Foo {
    var myProperty: Int = 0 {
        didSet {
            print("The value of myProperty changed from (oldValue) to (myProperty)")
        }
    }
}

myProperty 每次修改时都会打印其旧值和新值.只有 getter 和 setter,我需要这个:

myProperty prints its old and new value every time it is modified. With just getters and setters, I would need this instead:

class Foo {
    var myPropertyValue: Int = 0
    var myProperty: Int {
        get { return myPropertyValue }
        set {
            print("The value of myProperty changed from (myPropertyValue) to (newValue)")
            myPropertyValue = newValue
        }
    }
}

所以 willSetdidSet 代表了几行的经济性,并且字段列表中的噪音更少.

So willSet and didSet represent an economy of a couple of lines, and less noise in the field list.

这篇关于Swift 中 willSet 和 didSet 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆