在某些情况下,我可能想要将数据建模,将值限制在给定范围内.
例如,如果我想代表一个"哺乳动物",我可能想要将legs
属性限制为0-4.
我的第一次尝试如下所示:
class Mammal { var _numLegs:Int? var numLegs:Int { get { return _numLegs! } set { if 0...4 ~= newValue { self._numLegs = newValue } else { self._numLegs = nil } } } }
然而,这似乎并不令人满意,因为所有属性都是"公开的",没有什么能阻止类的客户设置Mammal._numLegs
为某个任意值.
有没有更好的方法呢?
只是为了好玩,我决定用@ jackWu的建议(+1)写一个片段,以便尝试那didSet
件事:
class Mammal { var numLegs:UInt? { didSet { if numLegs? > 4 { numLegs = nil } } } init() { numLegs = nil } }
它完美地运作.一旦你尝试将numLegs设置为5或更大,它就会自动缩小.请注意,我使用Uint来避免负腿量:)
我真的很喜欢这种优雅didSet
.
在这个特定的情况下,你想要一个property observer
,你可以像这样实现它:
class Mammal { init () { numLegs = 0 super.init() } var numLegs:Int { didSet: { if !(numLegs ~= 0...4) { numLegs = max(0,min(numLegs,4)) // Not sure if this is what you want though } } } }
虽然看着这个,但我不确定这是否会didSet
再次进行再次调用......我想这不会太糟糕,因为它会在第二次通过检查