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...
The shortest (but maybe not most efficient) way to clamp, is:
let clamped = [0, a, 5].sorted()[1]
Source: user tobr in a discussion on Hacker News
With Swift 5.1, the idiomatic way to achieve the desired clamping would be with property wrappers. A touched-up example from NSHipster:
@propertyWrapper
struct Clamping<Value: Comparable> {
var value: Value
let range: ClosedRange<Value>
init(wrappedValue: Value, _ range: ClosedRange<Value>) {
precondition(range.contains(wrappedValue))
self.value = wrappedValue
self.range = range
}
var wrappedValue: Value {
get { value }
set { value = min(max(range.lowerBound, newValue), range.upperBound) }
}
}
Usage:
@Clamping(0...5) var a: Float = 4.2
@Clamping(0...5) var b: Float = -1.3
@Clamping(0...5) var c: Float = 6.4