Reversing an Array in Swift
Published on: January 1, 2020You can reverse an Array, and any other Collection
in Swift using the reverse
method. For example
var input = [1, 2, 3]
print(input) // [1, 2, 3]
input.reverse()
print(input) // [3, 2, 1]
The code above takes an array (input
) and reverses it in-place using the reverse()
method. This only works if your array is mutable.
If you want to reverse an immutable array that's defined as let
, or if you don't want to alter the original input you can use reversed()
instead of reverse()
:
var input = [1, 2, 3]
print(input) // [1, 2, 3]
var reversed = input.reversed()
print(input) // [1, 2, 3]
print(reversed) // ReversedCollection<Array<Int>>(_base: [1, 2, 3])
The reversed()
method returns an instance of ReversedCollection
. It can be used much like a regular Collection
and you can convert it to a regular Array
as follows:
let reversedArray = Array(reversed)
print(reversedArray) // [3, 2, 1]
It's typically advised to avoid making this final conversion because ReversedCollection
doesn't compute the reversed array unless absolutely needed. Instead, it can iterate over the input array from the end to the start which is more efficient than reversing the entire array all at once. So only convert the result of reversed()
to an Array
explicitly if you run into problems otherwise which, in my experience, is almost never.