[swift-evolution] [Proposal] Safer half-open range operator
pyry.jahkola at iki.fi
Wed Apr 13 11:59:30 CDT 2016
> On 13 Apr 2016, at 17:53, Luis Henrique B. Sousa <lshsousa at gmail.com> wrote:
> (…) I totally agree with @Vladimir that we could have a more clear and swift-ly way to concisely wrap those operations.
> The behaviour pointed out by him looks very nice and doable to me.
> a = [1,2,3]
> a[-1..<6] - raises runtime error (right behavior by default, doesn't affect existing code)
> a[truncate: -1..<6] - produces [1,2,3] (the very behaviour I proposed initially)
> a[safe: -1..<6] - produces nil (i.e [T]?) (no runtime errors and makes it easy to handle unexpected results)
I don't feel strongly about this. Yes, if this were shorter to express, it would feel like nicer design. But what Haravikk and Chris L. already said seems to me as wiser design.
(@Vladimir: Besides, I'm sure `.clamped(to:)` wasn't invented for this purpose but for doing interval arithmetic on ranges. It just happens to somewhat work here.)
– Would this feature really provide a measurable benefit to developers?
– Under which circumstances do you find yourself with a past-the-end upper bound such as 6 where `a.count == 3`?
– …Let alone a negative start index like `-1`?
I find cases like these to be much more common in languages like Python and Ruby where e.g. `array[-2]` refers to the penultimate element. Swift doesn't seem to want to go there.
For the use cases I can think of, Swift 3—as the proposal currently goes <https://github.com/apple/swift/blob/swift-3-indexing-model/stdlib/public/core/Collection.swift#L724-L808>—already offers the following suitable methods:
array.prefix(maxLength) // no precondition
array.dropLast(n) // no precondition
array.dropFirst(n) // no precondition
array.suffix(maxLength) // no precondition
If these feel too clumsy to use, maybe we should focus on making them all more convenient. Ideally, that suggestion would apply to all `Collection`s.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution