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

Pyry Jahkola pyry.jahkola at iki.fi
Wed Apr 13 06:09:58 CDT 2016

> On 11 Apr 2016, at 15:23, Luis Henrique B. Sousa via swift-evolution <swift-evolution at swift.org> wrote:
> let a = [1,2,3]
> let b = a[0..<5]
> print(b)

In the swift-3-indexing-model branch <https://github.com/apple/swift/blob/swift-3-indexing-model/stdlib/public/core/Range.swift#L94>, you can clamp a range just like you could clamp intervals in Swift 2. So the following will work in the way you preferred:

    let b = a[a.indices.clamped(to: 0 ..< 5)]

It was suggested to extend `Collection` with a subscript like `a[safe: 0 ..< 5]` which resembles the current subsequence subscript <https://github.com/apple/swift/blob/swift-3-indexing-model/stdlib/public/core/Collection.swift#L82>. Alternatively, we could bring collections even closer to ranges by extending them with the equivalent `.clamped(to:)` method:

    let b = a.clamped(to: 0 ..< 5) // "safe" subsequence

— Pyry

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

More information about the swift-evolution mailing list