Swift
Reverse Range
Swift Programming
iOS Development
Coding Tutorial

Reverse Range in Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Reverse iteration is a common requirement when you process arrays, build undo flows, or walk time series from newest to oldest. Swift gives you more than one way to move backward, and each option has a different tradeoff around readability and index safety. This guide explains when to use reversed(), when to use stride, and how to avoid off by one mistakes.

How Reverse Iteration Works in Swift Ranges

Swift ranges are directional, so a half open range like 0..<count naturally moves forward. If you need backward traversal, you can either reverse an existing sequence or build a descending step with stride. Both are valid, but they communicate intent differently.

Use reversed() when you already have a range or collection and want to walk it in the opposite order. The result is a reversed view, which is efficient and does not copy data unless you ask for an array.

swift
1import Foundation
2
3let numbers = [10, 20, 30, 40, 50]
4
5for value in numbers.reversed() {
6    print(value)
7}
8
9for index in (0..<numbers.count).reversed() {
10    print("index \(index) value \(numbers[index])")
11}

The important detail is that index boundaries stay the same. You still use 0 as the first valid index and count - 1 as the last valid index. Reverse traversal changes order, not the valid bounds.

Choosing Between reversed() and stride

stride is better when you want explicit control over step size, bounds, or arithmetic progression. It works well for sampling every second element, stepping through pages, or iterating from an upper limit down to zero.

swift
1import Foundation
2
3let count = 6
4
5for i in stride(from: count - 1, through: 0, by: -1) {
6    print(i)
7}
8
9for even in stride(from: 10, through: 0, by: -2) {
10    print(even)
11}

through includes the end value, while to excludes it. That one keyword often decides whether your last iteration runs. If you are converting logic from a forward loop, check this boundary carefully.

In day to day code, a good rule is simple. Use reversed() when you conceptually reverse a sequence. Use stride when you conceptually count down by a step.

Building Safe Reverse Loops for Collections

Collection code becomes fragile when index math is duplicated across multiple loops. A safer pattern is to wrap traversal in a helper that centralizes bounds handling.

swift
1import Foundation
2
3func printLinesFromBottom(_ lines: [String]) {
4    guard !lines.isEmpty else {
5        print("No lines")
6        return
7    }
8
9    for i in stride(from: lines.count - 1, through: 0, by: -1) {
10        print("\(i): \(lines[i])")
11    }
12}
13
14printLinesFromBottom(["first", "second", "third"])

This version handles an empty collection up front, then performs a clear and bounded countdown. It is easy to test and easy to reuse.

For custom collections, prefer existing index APIs when possible. If you manually compute integer offsets, make sure the collection guarantees contiguous integer indices.

Common Pitfalls

  • Counting down from count instead of count - 1: count is one position past the last valid index. Start at count - 1 for array indexing.
  • Using to when you intended through: to excludes the lower bound, which can silently skip index zero.
  • Forgetting empty array handling: A countdown that starts at count - 1 fails when count is zero unless you guard first.
  • Converting every reversed view to Array: Keep lazy reversed sequences unless you truly need a copied collection.

Summary

  • Reverse traversal in Swift is best handled with reversed() or stride, depending on intent.
  • reversed() expresses sequence inversion, while stride expresses explicit countdown logic.
  • Boundary choices such as through versus to are the main source of reverse loop bugs.
  • Guard empty collections before index based reverse iteration.
  • Encapsulating reverse traversal in small helpers improves safety and readability.

Additional practice tip: create a small reproducible example before applying any fix to production code. A narrow test case clarifies assumptions, exposes edge cases, and makes your final implementation easier to review and maintain over time.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.