本文介绍了我们可以将getSet和setter一起使用willSet和didSet吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在快速阅读有关属性的willset和didset我知道我可以将它们与具有如下初始值的变量一起使用:

I was reading about willset and didset of properties in swiftI came to know that I can use these with variable having initial value like below:

var property = "name"
{
    willSet
    {
        print("property is about to changed")
    }
    didSet
    {
        if property == oldValue
        {
            print("values are same")
        }
        else
        {
            print("value changed")
        }
    }
}

property = "anothername"

所以我可以像下面这样使用willget和didset吗:

so can I use willget and didset like below:

var property2:String{

    willSet
    {
        print("value is about to change")
    }
    didSet
    {
        print("value is changes")
    }
}

它给了我这个错误:

non-member observing properties require an initializer
var property2:String{
    ^

所以任何人都可以向我解释这是怎么回事,我可以将getter和setter与willset和didset一起使用,例如:

so anyone can explain me what is going on here and can I use getter and setter with willset and didset together like:

var property2:String{

    get{return property2}
    set{propert2 = newValue}

    willSet
    {
        print("value is about to change")
    }
    didSet
    {
        print("value is changes")
    }
}

推荐答案

可以通过为属性提供默认值(如您的第一段代码一样)来解决表示缺少初始化程序的错误:

The error that says you lack an initializer can be solved by giving the property a default value like your first piece of code did:

var property2:String = "Some default value"{

    willSet
    {
        print("value is about to change")
    }
    didSet
    {
        print("value is changes")
    }
}

现在我将回答为什么您不能在计算属性上使用属性观察器.

Now I will answer why can't you use property observers on computed properties.

因为没有意义.

对于可设置的可计算属性,您已经具有设置器,因此您可以编写在设置器中设置值时要执行的任何代码..为什么需要额外的willSetdidSet?而且对于仅获取的计算属性,无法设置它,因此您希望什么时候执行willSetdidSet?

For a settable computed property, you already have the setter, so you can write whatever code you want to execute when the value is set in the setter. Why do you need an extra willSet or didSet? And for a get-only computed property, it can't be set so when do you expect willSet and didSet to be executed?

基本上,计算属性中的set块已经满足了willSetdidSet的目的.在willSet中编写的所有内容都可以在设置值之前在set中编写.设置值后,您在didSet中编写的所有内容都可以在set中编写.

Basically, the set block in computed properties already fulfils the purpose of willSet and didSet. Everything you write in willSet you can write it in set before you set the value. Everything you write in didSet you can write in set after you set the value.

另外,请注意,由于您在自己的getter中访问property2并将其设置在自己的setter中,因此您的第三个代码可能会导致堆栈溢出.

Also, note that your third code can cause a Stack Overflow since you are accessing property2 inside its own getter and setting it inside its own setter.

这篇关于我们可以将getSet和setter一起使用willSet和didSet吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 02:07