How to reverse elements of a sequence in Swift

Overview

The reverse() method is used to reverse a sequence in Swift.

Syntax

sequence.reverse()

Return value

This method returns the sequence, but with its elements reversed.

Example

// create sequences
var arr1 = [3, 45, 12, 1]
var arr2 = ["a", "b", "c", "d"]
// reverse arrays
arr1.reverse()
arr2.reverse()
// print results
print(arr1)
print(arr2)

Explanation

In the code above:

  • Lines 2 and 3: We create two arrays arr1 and arr2.
  • Lines 6 and 7: We reverse the arrays using the reverse() method.
  • Lines 10 and 11: We print the reversed arrays to the console.

Free Resources