When I use the for loop in Playground, everything worked fine, until I changed the first parameter of for loop to be the highest value. (iterated in descending order)
Is this a bug? Did any one else have it?
for index in 510..509
{
var a = 10
}
The counter that displays the number of iterations that will be executions keeps ticking...
If one is wanting to iterate through an array (
Array
or more generally anySequenceType
) in reverse. You have a few additional options.First you can
reverse()
the array and loop through it as normal. However I prefer to useenumerate()
much of the time since it outputs a tuple containing the object and it's index.The one thing to note here is that it is important to call these in the right order:
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray'sreverseEnumerator
)walks the array backward but outputs ascending indexes.
For Swift 2.0 and above you should apply reverse on a range collection
It has been renamed to .reversed() in Swift 3.0
You can consider using the C-Style
while
loop instead. This works just fine in Swift 3:Swift 4.0
If you want to include the
to
value:Apply the reverse function to the range to iterate backwards:
For Swift 1.2 and earlier:
It also works with half-open ranges:
Note:
reverse(1...10)
creates an array of type[Int]
, so while this might be fine for small ranges, it would be wise to uselazy
as shown below or consider the acceptedstride
answer if your range is large.To avoid creating a large array, use
lazy
along withreverse()
. The following test runs efficiently in a Playground showing it is not creating an array with one trillionInt
s!Test:
For Swift 2.0 in Xcode 7:
Note that in Swift 2.0,
(1...1_000_000_000_000).reverse()
is of typeReverseRandomAccessCollection<(Range<Int>)>
, so this works fine:For Swift 3.0
reverse()
has been renamed toreversed()
: