Swift Set sorted()

The sorted() method sorts the items of the set in a specific order (ascending or descending).

Example

var numbers: Set = [1, 3, 8, 5, 2]

// sort the numbers set var result = numbers.sorted()
print(result) // Output: [1, 2, 3, 5, 8]

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()

// set of strings
var names: Set = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben"]

// sort the names set var result1 = names.sorted()
print(result1) // set of integers var priceList: Set = [1000, 50, 2, 7, 14]
// sort the priceList set var result2 = priceList.sorted()
print(result2)

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

// set of strings
var names = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben"]

// sort the names set names.sorted(by: >)
print(names) // set of integers var priceList = [1000, 50, 2, 7, 14]
// sort the priceList set priceList.sorted(by: >)
print(priceList)

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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges