Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Last active May 17, 2021 20:25
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 ralfebert/486b14c618823af4d65e34e09e864c70 to your computer and use it in GitHub Desktop.
Save ralfebert/486b14c618823af4d65e34e09e864c70 to your computer and use it in GitHub Desktop.
extension Comparable {
mutating func clamp(_ limits: ClosedRange<Self>) {
self = min(max(self, limits.lowerBound), limits.upperBound)
}
mutating func clamp(_ limits: PartialRangeFrom<Self>) {
self = max(self, limits.lowerBound)
}
mutating func clamp(_ limits: PartialRangeThrough<Self>) {
self = min(self, limits.upperBound)
}
func clamped(_ limits: ClosedRange<Self>) -> Self {
var value = self
value.clamp(limits)
return value
}
func clamped(_ limits: PartialRangeFrom<Self>) -> Self {
var value = self
value.clamp(limits)
return value
}
func clamped(_ limits: PartialRangeThrough<Self>) -> Self {
var value = self
value.clamp(limits)
return value
}
}
let value = 25
value.clamped(10...20)
value.clamped(10...)
value.clamped(...20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment