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

Brent Royal-Gordon brent at architechies.com
Tue Dec 8 16:27:01 CST 2015


> 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.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list