How to sort a set using sorted() and the < operator in Swift
Overview
In Swift, the sorted() method is used to sort a set in <, is used with it as a parameter.
Syntax of sorted()
set.sorted()
Syntax using the sorted() method
Parameters
This method doesn't take any parameter.
Return value
It returns a set with its elements sorted in ascending order.
Syntax of <
set.sorted(by: <)
Syntax of using the < operator
Parameters
<: With this less-than operator, we can sort the elements of a set in ascending order. This is possible with the help of the sorted(by:) method.
Return value
It returns the same value as the sorted() method.
Example
// create some setsvar workers: Set = ["Evangeline", "CHiwendu", "Amara", "Bethany", "Diana"]var randomNumbers: Set = [12, 1, 45, 6, 90, 102, 88]// sort them using the sorted() and the < operatorlet sortedWorkers = workers.sorted()let sortedNumbers = randomNumbers.sorted(by: <)// print sorted setsprint(sortedWorkers)print(sortedNumbers)
Explanation
- Line 2–3: We create two sets and initialize them.
- Line 6: We sort the
workersset using thesorted()method. - Line 7: We sort the set,
randomNumbers, using thesorted(by:)method. Next, we supply the less-than operator<as a parameter to this method. Finally, we save the sorted result into another variable. - Line 10–11: We print the results to the console.