-
-
Save sturdysturge/bc2b51e2fba44694feb806475db9008d to your computer and use it in GitHub Desktop.
Comparable Clamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Comparable { | |
func clampFrom(min minValue: Self, to maxValue: Self) -> Self { | |
let clampedToMin = [minValue, self].max() ?? minValue | |
let clampedToBoth = [clampedToMin, maxValue].min() ?? maxValue | |
return clampedToBoth | |
} | |
} | |
var float = Float(0.5) | |
print(float.clampFrom(min: 0.5, to: 1)) //No effect, value is within range | |
float += 0.6 //Value is increased beyond range | |
print(float.clampFrom(min: 0.5, to: 1)) //Would be 1.1, now clamped to 1.0 | |
print((float + 0.6).clampFrom(min: 1, to: 1.5)) //Would be 1.7, now clamped to 1.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment