Reverse Range in Swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
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.
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.
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
countinstead ofcount - 1:countis one position past the last valid index. Start atcount - 1for array indexing. - Using
towhen you intendedthrough:toexcludes the lower bound, which can silently skip index zero. - Forgetting empty array handling: A countdown that starts at
count - 1fails whencountis 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()orstride, depending on intent. reversed()expresses sequence inversion, whilestrideexpresses explicit countdown logic.- Boundary choices such as
throughversustoare 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
- Right align text in android TextView
- Ripple effect on Android Lollipop CardView
- Room - Schema export directory is not provided to the annotation processor so we cannot export the schema
- Room - Schema export directory is not provided to the annotation processor so we cannot export the schema
- Room persistance library. Delete all
- RootViewController Switch Transition Animation
- Rotate Array in Swift
- Rotation methods deprecated, equivalent of ''didRotateFromInterfaceOrientation''?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.