Here is a clamp implementation I am using in a real project:
extension Comparable {
func clamped(from lowerBound: Self, to upperBound: Self) -> Self {
return min(max(self, lowerBound), upperBound)
}
func clamped(to range: ClosedRange<Self>) -> Self {
return min(max(self, range.lowerBound), range.upperBound)
}
}
extension Strideable where Self.Stride: SignedInteger {
func clamped(to range: CountableClosedRange<Self>) -> Self {
return min(max(self, range.lowerBound), range.upperBound)
}
}
https://github.com/fulldecent/FDWaveformView/blob/master/Source/FDWaveformView.swift#L573-L589
Open ranges do not have a clear enough answer for me. Especially in the
case of an empty range. Therefore the above implementation is the most
conservative.
- William Entriken