Skip to content

Instantly share code, notes, and snippets.

@leemorgan
Last active November 9, 2022 15:36
Show Gist options
  • Save leemorgan/bf1a0a1a8b2c94bce310 to your computer and use it in GitHub Desktop.
Save leemorgan/bf1a0a1a8b2c94bce310 to your computer and use it in GitHub Desktop.
clamp() in Swift
///Returns the input value clamped to the lower and upper limits.
func clamp<T: Comparable>(value: T, lower: T, upper: T) -> T {
return min(max(value, lower), upper)
}
//-----------------------------------------------
// Example usage
let proposedIndex = 6
let i = clamp(proposedIndex, 0, 5)
// What clamp() replaces
func getIndex(proposedIndex: Int) -> Int {
if proposedIndex < 0 {
return 0
}
else if proposedIndex <= 5 {
return proposedIndex
}
else {
return 5
}
}
@fulldecent
Copy link

There is also discussion here http://stackoverflow.com/a/43769799/300224 with a more detailed answer.

@lutes1
Copy link

lutes1 commented Nov 9, 2022

To avoid force casting you could do something like that since Self is Comparable

extension Comparable {
  func clamp(lower: Self, upper: Self) -> Self {
    return min(max(self, lower), upper)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment