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

William Entriken fulldecent at gmail.com
Wed May 17 09:39:25 CDT 2017


Here is a clamp implementation I am using in a real project:

```
extension Comparable {
    func clamped(from lowerBound: Self, to upperBound: Self) -> Self {
        return min(max(self, lowerBound), upperBound)
    }

    func clamped(to range: ClosedRange<Self>) -> Self {
        return min(max(self, range.lowerBound), range.upperBound)
    }
}

extension Strideable where Self.Stride: SignedInteger {
    func clamped(to range: CountableClosedRange<Self>) -> Self {
        return min(max(self, range.lowerBound), range.upperBound)
    }
}
```

https://github.com/fulldecent/FDWaveformView/blob/master/Source/FDWaveformView.swift#L573-L589

Open ranges do not have a clear enough answer for me. Especially in the
case of an empty range. Therefore the above implementation is the most
conservative.

- William Entriken
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170517/99019bb9/attachment.html>


More information about the swift-evolution mailing list