[swift-evolution] Feature proposal: Range operator with step
Dave Abrahams
dabrahams at apple.com
Thu Mar 24 16:18:08 CDT 2016
on Wed Mar 23 2016, Xiaodi Wu <swift-evolution at swift.org> wrote:
> So, in other words, you'd be satisfied with the following addition to
> the standard library?
>
> ```
> extension Range where Element: Strideable {
> func by(step: Element.Stride) -> StrideTo<Element> {
> return startIndex.stride(to: endIndex, by: step)
> }
> }
>
> /*
> example of usage:
>
> for i in (1..<10).by(2) {
> print(i)
> }
> */
> ```
My current thinking is that:
* `for x in 0.0..<3.0 {}` should probably be an error, because 1.0 is
not the obviously-right stride to use for non-integral numbers. That
would imply that floating types should not conform to Strideable,
which raises the question of whether Strideable should be folded into
the Integer protocol.
* `for x in (0.0..<20.0).striding(by: 1.3) {}` should work without
accumulating error
* `for x in 0..<3 {}` should work (obviously; that's the status quo)
* `for x in (0..<20).striding(by: 2)` should work
I think this might also handle the concerns that
https://github.com/apple/swift-evolution/blob/master/proposals/0051-stride-semantics.md
was trying to address.
If I thought extreme concision was important for this application, I'd be
proposing something like
for x in 0.0..<20.0//1.3 {}
but personally, I don't, which is why I propose `.striding(by: x)`
rather than simply `.by(x)`, the latter being more open to
misinterpretation.
--
Dave
More information about the swift-evolution
mailing list