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

查看:181
本文介绍了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中使用相同的代码,它们的目的是什么?

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天全站免登陆