[swift-evolution] [Proposal] Safer half-open range operator

Taras Zakharko taras.zakharko at googlemail.com
Mon Apr 11 10:25:58 CDT 2016

I do not think that this should be included in the default library as it is inconsistent with the behavior we generally have on collections (where user is responsible for correct indexing). However, it is quite trivial to define a new subscript operation, e.g. subscript(safe: Range)

— Taras

> On 11 Apr 2016, at 14: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 <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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160411/d9807746/attachment.html>

More information about the swift-evolution mailing list