Given:
let a = 4.2
let b = -1.3
let c = 6.4
I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...
Using the same syntax as Apple to do the min and max operator:
public func clamp(_ value: T, minValue: T, maxValue: T) -> T where T : Comparable {
return min(max(value, minValue), maxValue)
}
You can use as that:
let clamped = clamp(newValue, minValue: 0, maxValue: 1)
The cool thing about this approach is that any value defines the necessary type to do the operation, so the compiler handles that itself.