[swift-evolution] [draft] Add `clamped(to:)` to the stdlib

Jaden Geller jaden.geller at gmail.com
Wed Mar 15 21:57:12 CDT 2017


> On Mar 15, 2017, at 7:33 PM, Nicholas Maccharoli <nmaccharoli at gmail.com> wrote:
> 
> Right, there were a few things missing!
> Thanks so much for pointing them out everyone.
> 
> Dave - Great idea! I have updated the motivation section section as you suggested!
> 
> Neil - Yes I also think the wording could be a bit better but since the word `clamped` is already being used 
>           I thought I would keep it consistent. 
> 
> Sean - Looks as if its a term of art to me as well. 
> 
> Nate,
> 
> Good catch! Yes I also thing clamping on an empty range should be a fatal error as well.
> An empty range is impossible to create with `ClosedRange` so I left the implementation 
> of that alone, but it is possible with `Range` so I updated the extension on `Strideable` like so:
> 
> extension Strideable where Stride: Integer {
>     func clamped(to range: Range<Self>) -> Self {
>         if range.isEmpty { fatalError("Can't form Range with upperBound < lowerBound") }
>         return clamped(to: range.lowerBound...(range.upperBound - 1))
>     }
> }
> 
> 
> 
> Jaden,
> 
> Yeah I think a simple `if` check would work as well.

I would suggest using guard. It is more idiomatic Swift for something that “fails out”.

Also, I think this is a bad error message. The `Range` was already created! There was no problem forming it. It was passed as the argument, no problem at all. The problem is trying to *clamp* to an empty range, not forming an empty range. I would rephrase it to say something like "Cannot clamp to an empty range”. No reason to redefine what an empty range is by mentioning `upperBound < lowerBound`.

Cheers,
Jaden Geller
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170315/1f096b6e/attachment.html>


More information about the swift-evolution mailing list