Add clamped(in:)
jsbean opened this issue · comments
extension Comparable {
func clamped(by range: ClosedRange<Self>) -> Self {
if self < range.lowerBound {
return range.lowerBound
} else if self > range.upperBound {
return range.upperBound
}
return self
}
}
Or, invert it and add it to (Closed)Range
:
extension Range {
public func clamping(_ value: Bound) -> Bound {
return min(max(value, lowerBound), upperBound)
}
}
i prefer the first, this seems consistent with other languages. semantically, i think of it as a transformation on a value than a service provided by a range. the range is created for the purpose of the value rather than the other way around
let b = (0...2).clamping(a)
let c = a.clamped(by: 0...2)
Yeah, I think I agree.