Swift: The smallest excutable for-loop

Viewed 119

If lowerBound is greater than upperBound your code will crash

Why does this run (nothing will be outputted, but still runs, also, floating point can't be inputted so "<1" would seeming be "0"))...

for i in 1..<1 {}

But this doesn't...

for i in 1...0 {}

?

2 Answers

The former expresses "starting at 1 and incrementing by one, if the value is less than one, include it." That is a set with no values in it, but it's a reasonable thing to say.

The later expresses "starting at 1 and incrementing by one, until the value equals 0, include it." That is really a set of all positive integers, but in practice you definitely didn't mean that, and it is is instead explicitly defined to be an error.

Another way to say the same thing is to consider the former to be all integers greater than or equal to 1 and also less than 1. Again, that's an empty set.

The latter is a set of all values greater than or equal to 1 and less than or equal to 0. That's also an empty set, but almost certainly not what you meant, so it's defined to be an error.

The error message tells you the answer:

Can't form Range with upperBound < lowerBound

That is the only rule that matters.

How the range gets formed is irrelevant to that rule. It doesn't matter whether the operator that forms the range is ... or ..<. All that matters is that when we try to obey the operator and instantiate the range, it must turn out that the upper bound is not smaller than the lower bound.

Well, in 1..<1, the upper bound is not smaller than the lower bound. So it's a legal range.

It is also an "empty" range; it contains no integer (neither 0, nor 1, nor 2, nor any other integer). But it's still a range.

Now, if you think about it, that's a very valuable thing. It doesn't look valuable in your example, because you're using literals. But when the lower bound and upper bound come from variables, it's a very good thing that lo..<hi doesn't crash in the corner case where lo and hi happen to be equal! That case arises a lot, and for good reasons.

For example, consider cycling thru the elements of an array. If the array is empty, its indices are (you guessed it) 0..<0. You want it to be legal to cycle thru this array. Nothing happens, but it's not illegal. And that's just what this rule says.

Related