[swift-evolution] Add a `clamp` function to Algorithm.swift

Nicholas Maccharoli nmaccharoli at gmail.com
Fri Mar 10 01:20:01 CST 2017


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 <swift-evolution at swift.org> 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
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170310/87d64458/attachment.html>


More information about the swift-evolution mailing list