Swift Programming: getter/setter in stored property

前端 未结 5 2058
夕颜
夕颜 2020-12-28 11:35

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

5条回答
  •  盖世英雄少女心
    2020-12-28 11:49

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

提交回复
热议问题