Skip to content

Instantly share code, notes, and snippets.

@qRoC
Last active January 13, 2018 00:20
Show Gist options
  • Save qRoC/dfea8cfa5c59d3d659a56ab93809d811 to your computer and use it in GitHub Desktop.
Save qRoC/dfea8cfa5c59d3d659a56ab93809d811 to your computer and use it in GitHub Desktop.
Swift clamp protocol
///
public protocol ClampSupport {
func clamped(from lowerBound: Self, to upperBound: Self) -> Self
func clamped(from lowerBound: Self) -> Self
func clamped(to lowerBound: Self) -> Self
}
public extension ClampSupport where Self: Comparable {
@_transparent
func clamped(from lowerBound: Self, to upperBound: Self) -> Self {
return min(max(self, lowerBound), upperBound)
}
@_transparent
func clamped(from lowerBound: Self) -> Self {
return max(self, lowerBound)
}
@_transparent
func clamped(to lowerBound: Self) -> Self {
return min(self, lowerBound)
}
@_transparent
func clamped(to range: ClosedRange<Self>) -> Self {
return self.clamped(from: range.lowerBound, to: range.upperBound)
}
@_transparent
func clamped(from range: PartialRangeFrom<Self>) -> Self {
return self.clamped(from: range.lowerBound)
}
@_transparent
func clamped(to range: PartialRangeThrough<Self>) -> Self {
return self.clamped(to: range.upperBound)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment