Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created December 24, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturdysturge/bc2b51e2fba44694feb806475db9008d to your computer and use it in GitHub Desktop.
Save sturdysturge/bc2b51e2fba44694feb806475db9008d to your computer and use it in GitHub Desktop.
Comparable Clamp
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