It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.
What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:
var bottom = 13
var top = 42
var tooLow = 7
var clamped = min(top, max(bottom, tooLow)) -> 13
var justRight = 23
clamped = min(top, max(bottom, justRight)) --> 23
var tooHigh = 99
clamped = min(top, max(bottom, tooHigh)) --> 42
This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:
precedencegroup MinMaxPrecedence {
associativity: left
higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence
}
infix operator <> : MinMaxPrecedence
func <><T:Comparable>(a:T, b:T) -> T {
return a < b ? a : b
}
infix operator >< : MinMaxPrecedence
func ><<T:Comparable>(a:T, b:T) -> T {
return a < b ? b : a
}
Basically, this defines two new operators (<>
and ><
) that can be used between any type that adopts Comparable
. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:
var bottom = 13
var top = 42
var tooLow = 7
var justRight = 23
var tooHigh = 99
bottom >< tooLow <> top --> 13
bottom >< justRight <> top --> 23
bottom >< tooHigh <> top --> 42