What is the reversed() method in Swift?

Overview

The reversed() method in Swift returns a view that presents the elements of a collection in the reverse order.

Syntax

sequence.reversed()

Parameters

This method does not take any parameters.

Return value

The value returned is a view showing the elements of the sequence sequence in the reverse order.

Code example

// create some sequences
let ages = [34, 23, 46, 26]
let name = "Theodore"
// get reverse view
print(Array(ages.reversed()))
print(String(name.reversed()))

Code explanation

  • Lines 2–3: We create two sequences.
  • Lines 6–7: We invoke the reversed() method on the sequences that we created. Then, we print the resulting view to the console.

Free Resources