[swift-evolution] Add clamp(value: Bound) -> Bound to ClosedInterval

Kevin Ballard kevin at sb.org
Fri Feb 19 13:30:04 CST 2016

On Wed, Feb 17, 2016, at 05:10 PM, Dave Abrahams via swift-evolution wrote:
> on Wed Feb 17 2016, Kevin Ballard <swift-evolution at swift.org> wrote:
> > I'd like to see ClosedInterval gain a new method
> >
> >     /// Returns `value` clamped to `self`.
> >     func clamp(value: Bound) -> Bound
> >
> > This can't go on HalfOpenInterval (and therefore can't go on
> > IntervalType) because a half-open interval doesn't have a known
> > largest-contained-value (and in fact it can be empty), but it's
> > perfectly reasonable for ClosedInterval to have this.
> It's well-defined when the value is an Index (has discreet values).  But
> that whole protocol is probably not long for this world...
> (https://github.com/apple/swift/blob/master/test/Prototypes/CollectionsMoveIndices.swift)

You're right, clamp() can be well-defined for HalfOpenInterval if the value conforms to some protocol that enables the ability to find the previous value (such as BidirectionalIndexType), although it would have to return an optional value in that case since the interval itself may be empty.

But I don't have any particularly compelling reason to care about having clamp() for HalfOpenIntervals anyway, since all of my own uses have been with floating-point values.

-Kevin Ballard

More information about the swift-evolution mailing list