-1

I have one extension which helps me to range bound a value with min and max. There are different scenarios where I need to use a different type like Int, Float, Double, CGFloat. So for that, I have created multiple extensions like below.

extension Int {
    func clamp(min: Int, _ max: Int) -> Int {
        return Swift.max(min, Swift.min(max, self))
    }
}

extension CGFloat {
    func clamp (min: CGFloat, _ max: CGFloat) -> CGFloat {
        return Swift.max(min, Swift.min(max, self))
    }
}

So, how can I make it more generic by using generic type T which only confirms to take numeric values?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Parth Adroja
  • 13,198
  • 5
  • 37
  • 71

1 Answers1

2

Here's the extension I use. It uses nested conditionals instead of the max/min approach. This allows it to potentially short circuit one of the branches, which can improve performance (if it matters).

extension Comparable {
    func clamped(to r: ClosedRange<Self>) -> Self {
        let min = r.lowerBound, max = r.upperBound
        return self < min ? min : (max < self ? max : self)
    }
}

10.clamped(to: 0...5) // => 5
Alexander
  • 59,041
  • 12
  • 98
  • 151