The sort() method sorts the items of an array in a specific order (ascending or descending).
Example
sort() Syntax
The syntax of the array sort() method is:
array.sort(by: operator)
Here, array is an object of the Array class.
sort() Parameters
The sort() method can take one parameter:
- operator (optional) - If we pass greater-than operator
>, the sorted array is reversed (or sorted in Descending order)
sort() Return Value
The sort() method doesn't return any value. Rather, it changes the order of the original array.
Example 1: Swift Array sort()
Output
["Adam", "Ben", "Danil", "Fabiano", "Jeffrey"] [2, 7, 14, 50, 1000]
Here, we can see that the names array is sorted in ascending order of the string. For example, "Adam" comes before "Danil" because "A" comes before "D".
Similarly, the priceList array is sorted in ascending order.
Example 2: Sorting in Descending Order
Output
["Jeffrey", "Fabiano", "Danil", "Ben", "Adam"] [1000, 50, 14, 7, 2]
Here, to sort the elements in descending order, we have passed the > operator to the sort() method
Note: We can also pass the < operator to sort the elements in ascending order. However, if we do not pass any arguments, the sort() method will arrange the elements in ascending order by default.