[swift-evolution] [Proposal] Safer half-open range operator
Dave Abrahams
dabrahams at apple.com
Mon Apr 11 14:30:48 CDT 2016
on Mon Apr 11 2016, Haravikk <swift-evolution at swift.org> wrote:
> I like the idea in theory, but the question is; is it really safer to return a
> result that the developer may not have wanted, versus an error indicating that a
> mistake may have been made?
That's exactly the question. We've considered doing it both ways.
> I wonder if perhaps there could be an alternative, such as a variation
> of the operator like so:
>
> let b = a [0 &..< 5] // Equivalent to let b = a[0 ..< min(5, a.endIndex)],
> becomes let b = a[0 ..< 3]
>
> I’m just not sure that we can assume that an array index out of range error is
> okay without some kind of indication from the developer, as otherwise we could
> end up returning a partial slice, which could end up causing an error elsewhere
> where the size of the slice is assumed to be 5 but isn’t.
>
> On 11 Apr 2016, at 13:23, Luis Henrique B. Sousa via swift-evolution
> <swift-evolution at swift.org> wrote:
>
> This proposal seeks to provide a safer ..< (aka half-open range operator) in
> order to avoid **Array index out of range** errors in execution time.
>
> Here is my first draft for this proposal:
> https://github.com/luish/swift-evolution/blob/half-open-range-operator/proposals/nnnn-safer-half-open-range-operator.md
>
> In short, doing that in Swift causes a runtime error:
>
> let a = [1,2,3]
> let b = a[0..<5]
> print(b)
>
> > Error running code:
> > fatal error: Array index out of range
>
> The proposed solution is to slice the array returning all elements that are
> below the half-open operator, even though the number of elements is lesser
> than the ending of the half-open operator. So the example above would return
> [1,2,3].
> We can see this very behaviour in other languages, such as Python and Ruby
> as shown in the proposal draft.
>
> This would eliminate the need for verifications on the array size before
> slicing it -- and consequently runtime errors in cases when the programmer
> didn't.
>
> Viewing that it is my very first proposal, any feedback will be helpful.
>
> Thanks!
>
> Luis Henrique Borges
> @luishborges
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
--
Dave
More information about the swift-evolution
mailing list