[swift-evolution] Discussion: Move range (..., ..<) to a range() function
Jordan Rose
jordan_rose at apple.com
Tue Dec 8 18:24:10 CST 2015
> On Dec 8, 2015, at 14:27, Brent Royal-Gordon 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 think the … and ..< operators are a great, concise way to specify the bounds of an operation.
>
> However, that doesn’t mean this couldn’t use some work. Suppose we removed the Range-producing … and ..< operators, so that instead they always produce an IntervalType. Then we rename and rejigger Stride to work with intervals (remember, Strideable implies Comparable, and Comparable implies compatibility with IntervalType):
>
> struct Series<Bounds: IntervalType where Bounds.Bound: Strideable>: SequenceType {
> init(_ bounds: Bounds, by: Bounds.Bound.Stride) {
> …
> }
>
> …
> }
> extension Series where Bounds.Bound: DefaultStrideable {
> init(_ bounds: Bounds) {
> self.init(bounds, by: Bounds.Bound.defaultStride)
> }
> }
> protocol DefaultStrideable: Strideable {
> static var defaultStride: Self { get }
> }
>
> The Strideable and new DefaultStrideable protocols would have to be renamed, of course; this is just a sketch.
>
> Now your ordinary for loop looks like:
>
> for i in Series(1..<10) {
> ...
> }
>
> And it’s easy to reverse it:
>
> for i in Series(1..<10).reverse() {
> …
> }
>
> I’m not totally convinced this is a good idea—it makes the common count-up-by-one case more difficult—but if you’re going to redesign things, I think this is a better way to do it.
Don't forget that most Ranges are on collection indexes, not strideable types, and Int is used as a collection index.
Jordan
More information about the swift-evolution
mailing list