[swift-evolution] [Proposal draft] Add `Clamp` function to standard library

Nicholas Maccharoli nmaccharoli at gmail.com
Fri Sep 2 11:55:46 CDT 2016


The aim of this proposal is to introduce clamp functionality to the swift
standard library. The clamp function would take a value and a upper and
lower bounds to clamp the value to, ensuring that the return value of the
function is within the range specified by the upper and lower bounds.
Swift-evolution thread: Discussion thread topic for that proposal

The standard library already includes functionality for min and max but at
the time of this writing there is no global function for clamp. Adding a
clamp function would complement min and max really well and would also
eliminate the need for developers to write their own clamp functionality.

I propose that a global clamp function akin to min and max be added to the
standard library.

The implementation of the global clamp function would be as follows:

public func clamp<T : Comparable>(value: T, _ lower: T, _ upper: T) -> T {
  return max(lower, min(value, upper))

on existing code

There are no impacts on existing code, this proposal is purely additive.

Aside from not making the additions that this proposal wishes to make to
the standard library no other alternatives have been considered.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160903/5a478a8b/attachment.html>

More information about the swift-evolution mailing list