[swift-evolution] Proposal: Python's indexing and slicing

Jacob Bandes-Storch jtbandes at gmail.com
Fri Dec 18 15:49:29 CST 2015


Or perhaps some subscripts with parameter labels, like

extension Array {
    subscript(fromEnd distance: Int) -> Element {
        return self[endIndex - distance]
    }
}

[0, 1, 2][fromEnd: 1] // returns 2

Jacob Bandes-Storch

On Fri, Dec 18, 2015 at 1:46 PM, Joe Groff via swift-evolution <
swift-evolution at swift.org> wrote:

>
> On Dec 18, 2015, at 4:42 AM, Amir Michail via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Examples:
>
> >>> l=[1,2,3,4,5]
> >>> l[-1]
> 5
> >>> l[-2]
> 4
> >>> l[2:4]
> [3, 4]
> >>> l[2:]
> [3, 4, 5]
> >>> l[-2:]
> [4, 5]
> >>> l[:3]
> [1, 2, 3]
> >>> l[::2]
> [1, 3, 5]
> >>> l[::]
> [1, 2, 3, 4, 5]
>
>
> Accepting negative indices is problematic for two reasons: it imposes
> runtime overhead in the index operation to check the sign of the index;
> also, it masks fencepost errors, since if you do foo[m-n] and n is
> accidentally greater than m, you'll quietly load the wrong element instead
> of trapping. I'd prefer something like D's `$-n` syntax for explicitly
> annotating end-relative indexes.
>
> -Joe
>
>
> _______________________________________________
> 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/20151218/4d6a3449/attachment.html>


More information about the swift-evolution mailing list