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