Fix: Reverse for Loop in Swift Not Counting Down

Written by

in

Quick answer: Use stride(from:through:by:) with a negative step to count down and include the final value. Alternatively, create an ascending range and call reversed() on it. Use stride(from:to:by:) if the final value should be excluded.

Why this happens

A Swift range does not change direction because its first bound is larger than its second. An expression such as 510...509 is not a descending range: its lower bound is greater than its upper bound, so creating it fails at runtime. The old 510..509 syntax from early Swift examples is not the current half-open range syntax either.

For a countdown, specify the direction separately. Use stride with a negative step, or build a valid ascending range and iterate over its reversed() view. Both approaches work in a Playground and in a regular Swift target.

How to fix it

1. Use stride to count down

Use stride(from:through:by:) when the loop should include the ending value. Set by to a negative number to move downward:

for index in stride(from: 510, through: 509, by: -1) {
    print(index)
}
// 510
// 509

Here, 510 is the starting value, 509 is the inclusive limit, and -1 is the step. This is the closest replacement for the intended descending loop in the original example.

Choose stride(from:to:by:) instead when the ending value should be excluded:

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
// 5
// 4
// 3
// 2

Changing to to through would also print 1. The distinction matters when the last iteration performs an operation such as removing an item or updating a counter. Pick the version that matches whether the boundary itself belongs in the loop.

The step does not have to be -1. For example, this loop counts down by three:

for number in stride(from: 10, through: 1, by: -3) {
    print(number)
}
// 10
// 7
// 4
// 1

An inclusive limit does not force the loop to visit that value. If the step does not land on the limit, iteration stops before crossing it. For example, changing the limit above to 0 still ends at 1.

Make sure the sign of the step points toward the limit. A negative step is appropriate for counting down; a positive step is appropriate for counting up. stride is a global function, not a method on a range.

2. Reverse an ascending range

If you already know the lower and upper bounds and want every integer between them, create the range in ascending order and call reversed():

for index in (1...5).reversed() {
    print(index)
}
// 5
// 4
// 3
// 2
// 1

The parentheses apply reversed() to the complete range. The closed range 1...5 includes both endpoints, so reversing it starts at 5 and ends at 1.

A half-open range excludes its upper bound before it is reversed:

for index in (1..<5).reversed() {
    print(index)
}
// 4
// 3
// 2
// 1

Reversing changes the order, not which values the range contains. This makes reversed() a convenient choice for a step of one, while stride makes a larger or otherwise explicit step easier to read.

Do not write (5...1).reversed(): Swift must create the range before it can reverse it, and the bounds are invalid in that order. Write (1...5).reversed() instead.

3. Handle empty arrays when looping over indexes

For an array, a half-open range based on count works even when the array is empty:

let names = ["Ada", "Grace", "Katherine"]

for index in (0..<names.count).reversed() {
    print(index, names[index])
}
// 2 Katherine
// 1 Grace
// 0 Ada

When names.count is zero, 0..<names.count is empty and the loop runs zero times. Avoid constructing 0...(names.count - 1) without first checking for an empty array: it would have an invalid upper bound of -1.

If you only need the elements, iterate over them directly instead of calculating indexes:

for name in names.reversed() {
    print(name)
}

This avoids indexing altogether. Use the index-based version when the position is needed as well as the value.

4. Check older examples for outdated syntax

Some answers written for early Swift versions use reverse(...), a .reverse() method, or the range syntax ... For a current Swift countdown, use .reversed() on a valid range or use one of the stride functions shown above.

If a Playground still appears to run unexpectedly, reduce the example to a small range and print the index. Check the start, limit, step, and whether to or through is intended before putting the loop back into the larger calculation.

How to prevent it

  • Write range bounds in ascending order, even when you plan to iterate in reverse.
  • Decide explicitly whether the final value is included: use through or a closed range for inclusion, and to or a half-open range for exclusion.
  • Use a negative stride step for a countdown and check that its magnitude matches the intended sequence.
  • Test index loops with an empty collection as well as one containing elements.
  • Prefer direct element iteration when you do not need indexes.

FAQ

Why does 5...1 not count down?

The ... operator creates a closed range from a lower bound to an upper bound; it is not a countdown operator. Use (1...5).reversed() or stride(from: 5, through: 1, by: -1) instead.

Does reversed() exclude the last value?

No. It reverses the values already in the range. A closed range includes both endpoints, while a half-open range excludes its upper endpoint before reversal.

Should I use stride or reversed() for a large range?

Either is suitable for iterating over an integer range without explicitly creating an array of all its values. Use stride for a custom step; use reversed() when reversing an existing ascending range is clearer. Avoid wrapping the result in Array(...) unless you need to store every value.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.