When developing applications with Swift, there might be cases where you need to reverse a given array, such as when you want to display an array of messages or comments in chronological order from newest to oldest (or vice versa). This concise, example-based article will show you some different ways to get the job done.
Using the reversed() method
The reversed() method returns a collection of the ReversedCollection<Array<Element>> type, that presents the elements of its base collection in reverse order. You can turn the result into an array by using Array().
Example:
let numbers = [1, 2, 3, 4, 5]
let reversedNumbers = Array(numbers.reversed())
print(reversedNumbers)
// Output: [5, 4, 3, 2, 1]
let words = ["dog", "cat", "bird", "fish"]
let reversedWords = Array(words.reversed())
print(reversedWords)
// Output: ["fish", "bird", "cat", "dog"]
Using the reverse() method
Unlike the reversed() method, the reverse() method (whose name doesn’t end with “d”) reverses the elements of the original array in place.
Example:
var array = [1, 2, 3, 4, 5]
array.reverse()
print(array)
Output:
[5, 4, 3, 2, 1]
Using a for loop
Another solution is to use a for loop with an index variable that decrements from the last element to the first element of the array and appends each element to a new array.
Example:
let array = [1, 2, 3, 4, 5]
// create a new empty array
var reversedArray = [Int]()
// loop through the input array in reverse order
for i in stride(from: array.count - 1, through: 0, by: -1) {
reversedArray.append(array[i])
}
print(reversedArray)
Output:
[5, 4, 3, 2, 1]