Hi all, adding clamp to the standard lib is also something I'm interested in but looking at the latest posts about it and attempting to revive discussion over at the evolution post [Revision] Fixing SE-0177: Add clamp(to:) to the stdlib it doesn't seem to be moving anywhere unfortunately.
It seems the consensus was to try and go for a protocol oriented approach, however that ran in to some difficulties.
Having played around it with it myself I think there's definitely some design issues that need working out. Specifically, the case of
Int types and their
PartialRangeUpTo implementations have an unfortunate edge case which is, if you specify a
PartialRangeUpTo where the upper and lower bounds (explicit or implicitly in the case of
PartialRangeUpTo) are equal, then there is the risk of a runtime error. What's more, this will happen pretty frequently, and in the case of using
clamping(_:) to 'safely' access elements of an array, a zero length array will cause the very runtime error that was meant to be avoided!
Of course, one could guard against this and just return the lower bound, but this seems imprecise.
With that in mind, I would avoid implementation of clamped for
PartialRangeUpTo specifically for Ints, and I would agree that without support for the full set of ranges, they shouldn't be supported at all.
Here, I would vote to falling back to a simple
clamped(min:,max:_) free function to sit alongside
max(_:_:) in the stdlib.
I do believe there is a case for a clamped function for
FloatingPoint types, however. This is able to fit the full range of
RangeExpression types maintaining mathematical integrity (as far as I can tell). It also seems to gel well with the frequent need/use for
clamped functions in mathematical and computer graphics applications. It also simplifies the implementation.