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
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

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 to loop through an array of structs in Swift?

Looping through an array of structs in Swift is straightforward and can be done in several ways depending on what you need to achieve. Here’s how to do it:

question swift xcode August 12, 2020 How to remove a Swift package from a project in Xcode?

If you go to Xcode > File > Swift Packages, you can see options to add a new Swift package, update them, reset caches, and resolve package versions. However, you do not see an option to remove a particular Swift package.

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.