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 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 swiftui swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.

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: