Instance Method

reversed()

Returns a view presenting the elements of the collection in reverse order.

Declaration

func reversed() -> ReversedRandomAccessCollection<Array<Element>>

Discussion

You can reverse a collection without allocating new space for its elements by calling this reversed() method. A ReversedRandomAccessCollection instance wraps an underlying collection and provides access to its elements in reverse order. This example prints the elements of an array in reverse order:

let numbers = [3, 5, 7]
for number in numbers.reversed() {
    print(number)
}
// Prints "7"
// Prints "5"
// Prints "3"

If you need a reversed collection of the same type, you may be able to use the collection’s sequence-based or collection-based initializer. For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.

let reversedNumbers = Array(numbers.reversed())
print(reversedNumbers)
// Prints "[7, 5, 3]"

Complexity: O(1)

See Also

Sorting an Array

func sort()

Sorts the collection in place.

func sort(by: (Element, Element) -> Bool)

Sorts the collection in place, using the given predicate as the comparison between elements.

func sorted()

Returns the elements of the collection, sorted.

Beta
func sorted()

Returns the elements of the sequence, sorted.

Beta
func sorted(by: (Element, Element) -> Bool)

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

func swapAt(Int, Int)

Exchanges the values at the specified indices of the collection.

Beta