Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
@zaggo

This comment has been minimized.

Show comment
Hide comment
@zaggo

zaggo Jan 21, 2016

Thanks. The only thing I added to this is a assert(lower <= upper) before the return statement in order to catch accidental mixups with the lower/upper arguments...

zaggo commented Jan 21, 2016

Thanks. The only thing I added to this is a assert(lower <= upper) before the return statement in order to catch accidental mixups with the lower/upper arguments...

@davidlawson

This comment has been minimized.

Show comment
Hide comment
@davidlawson

davidlawson Feb 5, 2016

Alternative:

extension Comparable
{
    func clamp<T: Comparable>(lower: T, _ upper: T) -> T {
        return min(max(self as! T, lower), upper)
    }
}

Example usage:

let value = 7
let clamped = value.clamp(3, 6)

davidlawson commented Feb 5, 2016

Alternative:

extension Comparable
{
    func clamp<T: Comparable>(lower: T, _ upper: T) -> T {
        return min(max(self as! T, lower), upper)
    }
}

Example usage:

let value = 7
let clamped = value.clamp(3, 6)
@fulldecent

This comment has been minimized.

Show comment
Hide comment
@fulldecent

fulldecent May 3, 2017

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

fulldecent commented May 3, 2017

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

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