What is the sorted() method in Swift?
Overview
The sorted() method in Swift, when invoked on a sequence or array, returns the elements of the sequence in a sorted order.
Syntax
sequence.sorted()
Parameters
This method does not take any parameters.
Return value
This method returns the elements of the sequence in a sorted order.
Code example
// create arraysvar arr1 = [3, 4, 1]var arr2 = ["c", "e", "b", "d", "a"]var arr3 = [-3, 0.3, -1.1]// print sorted arraysprint(arr1.sorted())print(arr2.sorted())print(arr3.sorted())
Code explanation
- Lines 2–4: We create the array values.
- Lines 7–9: We invoke the
sorted()method on the arrays. Then, we print the results to the console.