如何将属性限制为范围?

j b*_*j b 4 properties swift

在某些情况下,我可能想要将数据建模,将值限制在给定范围内.

例如,如果我想代表一个"哺乳动物",我可能想要将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
        }
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,这似乎并不令人满意,因为所有属性都是"公开的",没有什么能阻止类的客户设置Mammal._numLegs为某个任意值.

有没有更好的方法呢?

Jea*_*nan 7

只是为了好玩,我决定用@ jackWu的建议(+1)写一个片段,以便尝试那didSet件事:

class Mammal {
    var numLegs:UInt? {
        didSet { if numLegs? > 4 { numLegs = nil } }
    }

    init() {
        numLegs = nil
    }
}
Run Code Online (Sandbox Code Playgroud)

它完美地运作.一旦你尝试将numLegs设置为5或更大,它就会自动缩小.请注意,我使用Uint来避免负腿量:)

我真的很喜欢这种优雅didSet.

  • 你对那些腿数不足的人有什么看法?你是负面的gigot偏执狂吗? (2认同)

Jac*_*ack 5

在这个特定的情况下,你想要一个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
            }   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然看着这个,但我不确定这是否会didSet再次进行再次调用......我想这不会太糟糕,因为它会在第二次通过检查