[swift-evolution] Discussion: Move range (..., ..<) to a range() function

Donnacha Oisín Kidney oisin.kidney at gmail.com
Tue Dec 8 15:06:46 CST 2015

```Personally, I think that the range operator is easier to understand than a free range function. People who already program might find it easier to understand a free function rather than ..<, which looks like special syntax, but I think beginners (especially in Python, actually) are really floored by range functions. Take, for example:

range(5)

To someone unfamiliar with the function, it could (quite reasonably) mean:

1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4
None of the above

In fact, for people unfamiliar with programming, I’d say that the correct answer is the least obvious. Compare that to:

0..<5

or:

0...4

I think the operator is much easier to understand, and more than makes up for the disadvantages associated with extra operators.

That said, I do think that Strideable is a little unclear. I can’t think of a much better option, though. Maybe something like:

extension Range where Element: Strideable {
public func by(n: Element.Stride) -> StrideTo<Element> {
return startIndex.stride(to: endIndex, by: n)
}
}
(0..<10).by(2) // [0, 2, 4, 6, 8]

But I’d also want that to work as a subscript.

> On 8 Dec 2015, at 19:01, Kyle Bashour via swift-evolution <swift-evolution at swift.org> wrote:
>
> Based on much of the discussion regarding removing C-style for-loops, I'd like to propose a discussion on revamping how range works in Swift. The lack of a reverse range operator and the fact and the range operator and stride() seem to do a lot of the same work have made me wonder why there isn't merely a range() function, as in Python.
>
> I believe this would be easier for newcomers to learn, remove the need for stride() (though there are probably use cases for stride() I don't know about, I haven't used it too much), and actually be more clear than ..< and ...
>
>
> Here are some examples of how it could work:
>
> range(10) // equivalent to 0..<10
> range(-1, to: 10) // equivalent to -1..<10
> range(10, through: 0) equivalent to (0...10).reverse()
> range(0, through: 10, by: 2) // equivalent to 0.stride(through: 10, by: 2)
>
> Or, to avoid a global function, .range() should probably be a function like stride, but with more features (equivalent to above)
>
> 10.range()
> -1.range(to: 10)
> 10.range(through: 0)
> 0.range(through: 10, by: 2)
>
> Would love thoughts on why this is good or bad, and if it's worth creating an actual proposal.
>
> Regards,
>
> Kyle
>
>  _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/860d705e/attachment.html>
```