Sling Academy
Home/Swift/Swift: 3 ways to reverse an array

Swift: 3 ways to reverse an array

Last updated: April 18, 2023

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]

Next Article: Sorting Arrays in Swift: Tutorial & Examples

Previous Article: 3 Ways to Concatenate Arrays in Swift

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)