[swift-evolution] [Draft]: Introducing a striding(by:) method on 3.0 ranges

Haravikk swift-evolution at haravikk.me
Sun Apr 10 06:53:44 CDT 2016

> On 10 Apr 2016, at 11:17, Brent Royal-Gordon <brent at architechies.com> wrote:
>> Why not just assign it the correct sign during the init function?
>> (0 ... 6).striding(by: 2) // [0, 2, 4, 6], end > start, so stride = by
>> (6 ... 0).striding(by: 2) // [6, 4, 2, 0], start > end, so stride = -by
> One reason not to do it this way is that, if we extend `striding(by:)` to other collections, they will not be as easy to walk backwards through as this. You will have to do something like `collection.reversed().striding(by:)` which will be a hassle.

Any thoughts on the alternative I mentioned a little earlier to define overloads instead of positive/negative? i.e- you would have two methods, .striding(forwardBy:) and .striding(backwardBy:). In addition to eliminating the use of a negative stride to indicate direction, this has the advantage that .striding(backwardBy:) can be defined only for types with a ReverseIndex or only for collections (as you can stride through a sequence, but only by going forward).

This should also make documentation a bit clearer, otherwise you’ve got the caveat that to go backwards requires a negative value, but only if the type supports that, which a developer would then need to check. Instead it either has the backwardBy variant or not.

I know that advance(by:) supports negative values, but this is actually something I wouldn’t mind seeing changed as well, as it has the same issues (passing a negative value in looks fine until you realise the type is a ForwardIndex only). It would also allow us to define Distance types that don’t support a direction, since this would be given by the choice of method called instead.

Of course I’d still like to be able to define 6 … 0 or whatever, but this would at least eliminate what I dislike about using negatives for direction.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160410/d6f30f33/attachment.html>

More information about the swift-evolution mailing list