I’m ok with doing it as an extension on `Comparable`, although we should add an overload for regular ranges, too.
- Dave Sweeris
How would the semantics of that work?
Good questions! I was mostly thinking about how often we do stuff like “for i in 0 ..< arr.count”, and that it’d be handy to not have to switch over to using ClosedRange just to be able to clamp to it. To answer your questions, though…
Should “16.clamped(to: 0..<10)” produce 9 or 10?
What about “16.clamped(to: 0..<0)”, which is an empty range?
For `Int`? Crash (which, until about 5 minutes ago, is what I thought would happen if you tried to create a range that’s empty like that). For types that support it, I’d say NaN or something like “nil”/“empty” is the most appropriate return value
Does “16.0.clamped(to: 0..<10)” yield 10.0 or the next-smaller representable Double?
Next-smaller, IMHO. It’s not exactly semantically correct, but AFAIK that’s as correct as Float/Double can be.
Mostly though I’d really like to be able to clamp to array indices, which are pretty much always written as a `Range`, rather than a `ClosedRange`. We could write the function for `Range` to only be generic over `Comparable&Integer`, if the floating point corner cases are too much.
- Dave Sweeris
On Mar 10, 2017, at 11:32 AM, Nevin Brackett-Rozinsky via swift-evolution <firstname.lastname@example.org> wrote:
On Fri, Mar 10, 2017 at 4:16 AM, David Sweeris via swift-evolution <email@example.com <mailto:firstname.lastname@example.org>> wrote: