Last active
January 13, 2018 00:20
-
-
Save qRoC/dfea8cfa5c59d3d659a56ab93809d811 to your computer and use it in GitHub Desktop.
Swift clamp protocol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// | |
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