Swift编程:存储属性中的getter / setter [英] Swift Programming: getter/setter in stored property

查看:131
本文介绍了Swift编程:存储属性中的getter / setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中覆盖存储属性的setter?

How do I overwrite the setter of stored property in Swift?

在Obj-C中,我可以覆盖它的setter,但是Swift似乎并不高兴关于用于存储属性的getter / setter。

In Obj-C, I can overwrite its setter, but Swift doesn't seem to be happy about getter/setters being used for stored property.

假设我有一个 Card 类,其中包含一个名为<$的属性C $ C>秩。我不希望客户端给它任何无效值,因此,在objective-C中,我可以覆盖 setRank ,以便它执行额外的检查。但是Swift中的 willSet 似乎没有帮助,因为 newValue 是不变的,分配<$ c是没有意义的$ c> rank 因为将在循环中调用setter。

Say I have a Card class with a property called rank. I don't want the client to give it any invalid value, therefore, in objective-C, I can overwrite setRank so that it performs additional check. But willSet in Swift doesn't seem to help because newValue is constant and it makes no sense to assign rank because setter will be called in a loop.

推荐答案

好的。通过Swift上的Apples文档阅读我发现这个

Ok. Reading through Apples documentation on Swift I found this:


如果为自己的didSet观察者中的属性赋值,
您指定的新值将替换为的值。只需设置。

If you assign a value to a property within its own didSet observer, the new value that you assign will replace the one that was just set.

所以你需要做的就是:

var rank: Int = 0 {
    didSet {
        // Say 1000 is not good for you and 999 is the maximum you want to be stored there
        if rank >= 1000  {
            rank = 999
        }
    }
}

这篇关于Swift编程:存储属性中的getter / setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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