Loading...

How to iterate an array in reverse in Swift?

question swift
Ram Patra Published on August 9, 2020
Version - Swift 5.0+

From Swift 5.0, you can use any of the following approaches to iterate an array in reverse.

A. Using reversed() method:

Example 1:

let numbers = (0 ... 3).reversed()

for num in numbers {
    print(num)
}

Output:

3
2
1
0

Example 2:

let languages = ["Java", "Swift", "Go"]

for language in languages.reversed() {
    print("\(language)")
}

Output:

Go
Swift
Java

B. Using stride() method:

Example 1:

let sequence = stride(from: 3, to: -1, by: -1)

for index in sequence {
    print(index)
}

Output:

3
2
1
0

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on August 9, 2020
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift November 17, 2023 How do get the string value of an enum in Swift?

In Swift, to get the string value of an enum, you typically have a couple of approaches depending on the enum’s definition. Let’s go through them:

question swiftui macos September 3, 2024 How to open and close windows programmatically in SwiftUI?

To open or close a window programmatically from outside that window using environment variables, you need to leverage the new openWindow (macOS 13+) and dismissWindow (macOS 14+) environment variables. This environment variables allow you to programmatically open and close a window by its identifier.

September 5, 2025 Automatically generate appcast.xml and DMG files for your Mac app updates

In this blog post we will see how we can fully automate macOS app updates with Sparkle 2 + GitHub Actions + GitHub Pages. We will build, notorize, sign, auto-generate appcast.xml and DMG files, etc. using GitHub Actions whenever you create a new release (this can be changed to on commit too).

Like my work?

Please, feel free to reach out. I would be more than happy to chat.