Ios – Swift Programming: getter/setter in stored property

iosswift

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

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

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.

Best Answer

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

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.

So all you have to do is this:

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
        }
    }
}
Related Topic