ClosedRange: is there no built-in method to ensure a value is within its bounds?

I couldn't find a method to do this in ClosedRange, basically something simple like this:

extension ClosedRange {
    /// Force the value to be within the lower and upper bounds of this range
    /// - Parameter value: some value
    /// - Returns: a value within the bounds of this range
    func boundWithin(_ value: Bound) -> Bound {
        max(lowerBound, min(value, upperBound))
    }
}
  1. should this method be built-in to CloseRange?
  2. Can you help me come up with a better name and signature of my method above? There is clamped already, is clamped here better?

Edit:

got this warning:

Use of 'max' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'ClosedRange' which comes via a conditional conformance

Use 'Swift.' to continue to reference the global function

What's the proper thing to do? Swift.max, Swift.min?

or add where some_type to my extension? If so, what's the type?

1 Like

This has been discussed a lot.

2 Likes

I haven't read those other threads. Just glancing at them, I didn't see this, but it's probably in there somewhere. I think it makes more sense to reverse your arguments.

public extension Comparable {
  func clamped(to limits: ClosedRange<Self>) -> Self {
    min(max(limits.lowerBound, self), limits.upperBound)
  }
public extension Strideable where Stride: SignedInteger {
  func clamped(to limits: Range<Self>) -> Self {
    clamped(to: ClosedRange(limits))
  }
}
let indices = [0, 1].indices
XCTAssertEqual((-3).clamped(to: indices), 0)
XCTAssertEqual(22.clamped(to: indices), 1)
2 Likes

:+1: clamped(to:) sounds better.

I was looking in ClosedRange for this so I would not have found this even if it exist already and clamped is not a name I would think of.

1 Like

We have a thread on this as pointed out by @phoneyDev !

Please feel free to come over and join the conversation!

Terms of Service

Privacy Policy

Cookie Policy