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 sequencesvar arr1 = [3, 45, 12, 1]var arr2 = ["a", "b", "c", "d"]// reverse arraysarr1.reverse()arr2.reverse()// print resultsprint(arr1)print(arr2)
Explanation
In the code above:
- Lines 2 and 3: We create two arrays
arr1andarr2. - Lines 6 and 7: We reverse the arrays using the
reverse()method. - Lines 10 and 11: We print the reversed arrays to the console.