[swift-evolution] [Idea] Add `bounds` function to standard library

Nicholas Maccharoli nmaccharoli at gmail.com
Thu Aug 25 04:05:25 CDT 2016


Swift Evolution Community,

In the standard library there is a `min` and a `max` function but there
isn't
a `bounds` function, or a function that takes a value and an upper and
lower bound and returns that value if it is within the specified range or
if not the closer of the lower or upper values supplied to the `bounds`
function.
(Other possible names for such a function could be something like `clamp`,
or `clip`)

I personally see merit in adding a function to bound the value of a
variable within a range and think it would be simple to write with the
existing implementations of `min` and `max` with something like:

    public func bounds<T : Comparable>(value: T, _ lower: T, _ upper: T) ->
T {

        return max(lower, min(value, upper))

    }

Does this sound like something the community thinks would be worthwhile to
add?

If so I would love to write a quick proposal.


- Nick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160825/034c9818/attachment.html>


More information about the swift-evolution mailing list