There are a cases where I might want to model data where it makes sense for a value to be restricted to a given range.
For example, if I want to represent a "mammal", I might want to restrict a legs
property to 0–4.
My first attempt is shown below:
class Mammal {
var _numLegs:Int?
var numLegs:Int {
get {
return _numLegs!
}
set {
if 0...4 ~= newValue {
self._numLegs = newValue
}
else {
self._numLegs = nil
}
}
}
}
However, this seems unsatisfactory since all properties are "public" there is nothing stopping the customer of the class from setting Mammal._numLegs
to some arbitrary value.
Any better ways to do it?