The sorted() method sorts the items of the set in a specific order (ascending or descending).
Example
sorted() Syntax
The syntax of the set sorted() method is:
set.sorted(by: operator)
Here, set is an object of the Set class.
sorted() Parameters
The sorted() method can take one parameter:
- operator (optional) - If we pass greater-than operator
>, the set is reversed (or set in descending order)
sorted() Return Value
The sorted() method returns a sorted array.
Example 1: Swift Set sorted()
Output
["Adam", "Ben", "Danil", "Fabiano", "Jeffrey"] [2, 7, 14, 50, 1000]
Here, we can see that the names set is sorted in ascending order of the string. For example, "Adam" comes before "Danil" because "A" comes before "D".
Similarly, the priceList set is set in ascending order.
Example 2: Sort 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 sorted() method
Note: We can also pass the < operator to sort the elements in ascending order. However, if we do not pass any arguments, the sorted() method will arrange the elements in ascending order by default.