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
Ram Patra Published on August 9, 2020
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift October 30, 2023 How to convert Color type to hex and vice-versa while retaining alpha information?

The below should work both on macOS and iOS with one minor change. That is, use UIColor instead of NSColor if you’re planning to use it for iOS.

question macOS swift March 14, 2021 How to detect Escape key pressed in macOS apps?

Like Delete key, detection of Escape key press is also slightly different than detecting general key presses.

June 7, 2020 How to add Global Key Shortcuts to your macOS app using MASShortcut

Adding Global Keyboard Shortcuts to your macOS app can be a pain as there isn’t a Cocoa API for the same. You would have to rely on the old, most of which are deprecated, Carbon API.