Last active
May 17, 2021 20:25
-
-
Save ralfebert/486b14c618823af4d65e34e09e864c70 to your computer and use it in GitHub Desktop.
This file contains 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
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