Skip to content

Instantly share code, notes, and snippets.

@Shilo
Forked from leemorgan/Clamp.swift
Created June 8, 2022 15:08
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 Shilo/bd463c155b312a8d9230962d04a80e93 to your computer and use it in GitHub Desktop.
Save Shilo/bd463c155b312a8d9230962d04a80e93 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment