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

Nicholas Maccharoli nmaccharoli at gmail.com
Thu Mar 9 20:43:57 CST 2017


Dave,

Thanks for the feedback!

Yes, there is no explicit need to make `clamp` a global function, and the
extension you proposed would work just fine I think.

`CountableClosedRange` already provides a `clamped(to:)` method but that
does not suit the use case I was thinking of wanting to receive a single
scalar return value rather than a range.

Any chance of dumping `min` and `max` as global functions?
There is already an extension on `Array` for `min` and `max` but that might
carry the overhead of creating an array every time a `min` or `max` is
performed, unless there was some compiler optimization magic that could
come to the rescue.

- Nick

On Fri, Mar 10, 2017 at 10:44 AM, David Sweeris <davesweeris at mac.com> wrote:

>
> On Mar 9, 2017, at 5:37 PM, Nicholas Maccharoli via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Swift Evolution,
>
> Having a`clamp` function available in the standard library would
> complement `min` and `max` really well.
>
> I mentioned this before when the discussion for Swift 4 was still in stage
> 1, but now that stage 2 has started I thought it might be worth while to
> bring up again.
>
> Still needs some work, but here is the draft proposal I wrote previously
>
> https://github.com/Nirma/swift-evolution/commit/
> a51c543a76e9a1021996fb4b617311a588e7f397
>
> Basically it boils down to something like this.
>
> public func clamp<T : Comparable>(value: T, _ lower: T, _ upper: T) -> T {
>   return max(lower, min(value, upper))
> }
>
>
>
> What does the community think?
>
>
> IIRC, we’ve been avoiding top-level functions lately… What about as an
> extension on Range?
>
> extension Range {
>     func clamp(_ x: Bound) -> Bound {
>         return max(lowerBound, min(x, upperBound))
>     }
> }
>
>
> - Dave Sweeris
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170310/79bcc26f/attachment.html>


More information about the swift-evolution mailing list