Nevin,
Yeah I think this works well as an extension on `Comparable`,
`foo.clamped(to: 1...100)` seems pretty natural.
Why not go one step further and move the versions of min, max that take two
arguments on over to `Comparable` as a protocol extension?
Perhaps something like this?
extension Comparable {
func max(with value: Self) -> Self {
if value > self {
return value
}
return self
}
func min(with value: Self) -> Self {
if value < self {
return value
}
return self
}
func clamped(to range: ClosedRange<Self>) -> Self {
let selfUpperMin = range.upperBound.min(with: self)
return range.lowerBound.max(with: selfUpperMin)
}
}
- Nick
On Fri, Mar 10, 2017 at 1:41 PM, Nevin Brackett-Rozinsky via
swift-evolution <[email protected]> wrote:
> Iād be on board with an extension of Comparable so you could write
> ā16.clamped(to: 0...10)ā. Something along the lines of:
>
> extension Comparable {
> func clamped(to range: ClosedRange<Self>) -> Self {
> return max(range.lowerBound, min(self, range.upperBound))
> }
> }
>
> Nevin
>
> _______________________________________________
> swift-evolution mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution