[swift-evolution] Feature proposal: Range operator with step

Xiaodi Wu xiaodi.wu at gmail.com
Wed Mar 23 21:36:35 CDT 2016


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)
}
*/
```


On Wed, Mar 23, 2016 at 6:02 PM, Haravikk via swift-evolution
<swift-evolution at swift.org> wrote:
> I’m behind the idea in principle, but I’m not so sure we need a new keyword
> for this:
>
> for eachIndex in (1 ..< 10).by(2) { … }
>
> The above would be adequate I thin, and just requires a new method on ranges
> and similar types. This is being discussed, among other things, in the
> c-style for loop discussion, as these were recently removed but without a
> replacement for this type of use-case.
>
> On 23 Mar 2016, at 21:40, David Knothe via swift-evolution
> <swift-evolution at swift.org> wrote:
>
> Hi,
>
> I am new to Swift mailing list so I don’t know if this topic has already
> been discussed.
>
> I like Swift's range operators ..< and …
> What I am missing though is an easy operator to create a range with a
> specified step. Currently, if you would want to iterate over some odd
> numbers, you had to write:
> for i in 1.stride(through: 7, by: 2) { … }
> What I think would be simpler and more convenient would be something like
> the following:
> for i in 1 … 7 step 2 { … } . Another option would be  for i in 1 … 7; 2 { …
> }
> The keyword ‚step‘ in this context clearly corresponds to the step of the
> range to create or to iterate over.
>
> Essentially this is a syntactic sugar that makes it easy to create ranges
> with a step ≠ 1. What do you think?
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>


More information about the swift-evolution mailing list