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 macOS swift March 14, 2021 How to ignore mouse events in a view or window in macOS?

You can ignore mouse events in a window/view by adding just a single line of code.

question swift October 22, 2023 How to not break automatically in switch statements in Swift?

In Swift, the switch statement doesn’t automatically fall through to the next case. Each case block is designed to execute only the code within that case, and it doesn’t continue to the next case unless you use the fallthrough keyword.

question macOS swift August 14, 2020 How to detect Delete key press in Swift?

Delete key press detection is slightly different than other keys. It uses NSDeleteCharacter like below: