reverse an array in swift

To reverse an array in Swift, you can utilize the reversed() method on the array. This method returns a reversed ReversedCollection view of the original array. To obtain the reversed array, you can then call the Array initializer on the ReversedCollection view.

Here's an example code snippet:

main.swift
var arr = [1, 2, 3, 4, 5]
let reversedArr = Array(arr.reversed())

print(reversedArr) // Output: [5, 4, 3, 2, 1]
113 chars
5 lines

In the above code snippet, we first define an array arr with some elements. Then, we call the reversed() method on arr to obtain a ReversedCollection view of the array, which we store in the variable reversedArr. Finally, we call the Array initializer to obtain the actual reversed array and print it to the console.

Note that the reversed() method does not modify the original array. If you want to modify the original array in place, you can use the reverse() method instead:

main.swift
var arr = [1, 2, 3, 4, 5]
arr.reverse()

print(arr) // Output: [5, 4, 3, 2, 1]
79 chars
5 lines

In this case, we call the reverse() method on the arr array, which modifies the original array in place and reverses its order. We then print the modified arr array to the console.

related categories

gistlibby LogSnag