I'm looking for a more elegant way to create bounded limiters for numbers, primarily to be used in setters. There are plenty of techniques for determining whether a value falls within bounds, but I don't see any native functions for forcing an incoming value to conform to those bounds.
The accepted answer here comes close but I want to cap the values rather than merely enforce them.
Here's what I have so far. I'm not sure about the Int extension. And I'd prefer to collapse the if-else
into a single elegant line of code, if possible. Ideally I'd like to shorten the actual implementation in the struct
, as well.
extension Int {
func bounded(_ min: Int, _ max: Int) -> Int {
if self < min {
return min
} else if self > max {
return max
} else {
return self
}
}
}
print(5.bounded(4, 6)) // 5
print(5.bounded(1, 3)) // 3
print(5.bounded(6, 9)) // 6
// Used in a sentence
struct Animal {
var _legs: Int = 4
var legs: Int {
get {
return _legs
}
set {
_legs = newValue.bounded(1, 4)
}
}
}
var dog = Animal()
print(dog.legs) // 4
dog.legs = 3
print(dog.legs) // 3
dog.legs = 5
print(dog.legs) // 4
dog.legs = 0
print(dog.legs) // 1