Standard way to "clamp" a number between two values in Swift

Viewed 32927

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...5, such that:

a -> 4.2
b -> 0
c -> 5

I know I can do the following:

let clamped = min(max(a, 0), 5)

Or something like:

let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

There may not be, and if so, that's also an answer I'll happily accept.

9 Answers

Using the same syntax as Apple to do the min and max operator:

public func clamp<T>(_ 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.

2020. The extremely simple way.

extension Comparable {
    func clamped(_ f: Self, _ t: Self)  ->  Self {
        var r = self
        if r < f { r = f }
        if r > t { r = t }
        // (use SIMPLE, EXPLICIT code here to make it utterly clear
        // whether we are inclusive, what form of equality, etc etc)
        return r
    }

While I truly love ranges in Swift, I really think the absolutely standard syntax for a clamp function ("for 50 years now in every computer language") is just simpler and better:

x = x.clamped(0.5, 5.0)

Until it is built-in to Swift, really I think that's best.

Philosophical corner:

IMO the two values in a clamp function are not really a 'range' - they're just "two values".

(Just for example: it's completely common in game code to have the two dynamic values sometimes be in the "wrong order" (i..e, the desired result is something outside) or the same (the result is just that value).)

An opinion on end-naming ...

On everything we do, we insist on explicitly stating whether inclusive or exclusive. For example if there's a call

randomIntUpTo( 13 )

in fact we will name it

randomIntUpToExclusive( 13 )

or indeed "inclusive" if that is the case. Or depending on the language something like

randomInt(fromInclusive:  upToExclusive: )

or whatever the case may be. In this way there is absolutely never ever ever a unity error, and nothing needs to be discussed. All code names should be self-documenting. So indeed, for us, the function above would be named

func clamped(fromExclusive: Self, toExclusive: Self)

or whatever describes it.

But that's just us. But it's the right thing to do :)

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

Following up on @Fattie's answer and my comment, here's my suggestion for clarity:

extension Comparable {
    func clamped(_ a: Self, _ b: Self) -> Self {
        min(max(self, a), b)
    }
}

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

Extending FixedWidthInteger and creating an instance generic method to accept a RangeExpression and taking care of the edge cases:

extension FixedWidthInteger {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.dropLast().upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.advanced(by: -1), self)
        default: return self
        }
    }
}

Playground testing:

100.clamped(with: 1...)     // 100
100.clamped(with: ..<100)   // 99
100.clamped(with: ...100)   // 100
100.clamped(with: 1..<100)  // 99
100.clamped(with: 1...100)  // 100

0.clamped(with: 1...)       // 1
0.clamped(with: ..<100)     // 0
0.clamped(with: ...100)     // 0
0.clamped(with: 1..<100)    // 1
0.clamped(with: 1...100)    // 1

To achieve the same results with a FloatingPoint implementation you can use its nextDown property for the edge cases:

extension BinaryFloatingPoint {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.upperBound.nextDown, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.nextDown, self)
        default: return self
        }
    }
}

Playground testing:

let value = 100.0

value.clamped(with: 1...)     // 100
value.clamped(with: ..<100)   // 99.99999999999999
value.clamped(with: ...100)   // 100
value.clamped(with: 1..<100)  // 99.99999999999999
value.clamped(with: 1...100)  // 100
Related