[swift-evolution] [draft] Add `clamped(to:)` to the stdlib
Nicholas Maccharoli
nmaccharoli at gmail.com
Wed Mar 15 22:21:53 CDT 2017
Jaden,
Yes that error message is not so great.
As for the use of guard `if someCondition { fatalError(...)}` seems to be
a common way of phrasing fatal errors
in the standard library but guard works just as well.
I updated the proposal to have the following definition:
extension Strideable where Stride: Integer {
func clamped(to range: Range<Self>) -> Self {
guard !range.isEmpty { fatalError("Can not clamp to an empty
range.") }
return clamped(to: range.lowerBound...(range.upperBound - 1))
}
}
- Nick
On Thu, Mar 16, 2017 at 11:57 AM, Jaden Geller <jaden.geller at gmail.com>
wrote:
>
> 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/20170316/edb88ea5/attachment-0001.html>
More information about the swift-evolution
mailing list