Reversing an Array in SwiftPublished on: January 1, 2020
You can reverse an Array, and any other
Collection in Swift using the
reverse method. For example
In-app purchases made easy. RevenueCat provides everything you need to implement, manage, and analyze in-app purchases without managing servers or writing backend code.
Try RevenueCat now
This sponsored message helps keep the content on this site free. Please check out this sponsor as it directly supports me and this site.
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
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])
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.