Swift – Get Sorted Elements of a Set
To get sorted elements of a Set in Swift, call sorted() method on this Set. sorted() returns elements of Set sorted in ascending order as an Array.
Examples
In the following example, we take a Set nums
and sort the elements in ascending order using sorted() method.
main.swift
</>
Copy
let nums: Set = [2, 4, 6, 18, 10]
let result = nums.sorted()
print("Original : \(nums)")
print("Sorted : \(result)")
Output
Original : [18, 2, 10, 4, 6]
Sorted : [2, 4, 6, 10, 18]
Program ended with exit code: 0
Now, let us take a Set of Strings fruits
, and get sorted elements as an array.
main.swift
</>
Copy
let fruits: Set = ["apple", "mango", "banana"]
let result = fruits.sorted()
print("Original : \(fruits)")
print("Sorted : \(result)")
Output
Original : ["banana", "apple", "mango"]
Sorted : ["apple", "banana", "mango"]
Program ended with exit code: 0
Conclusion
In this Swift Tutorial, we learned how to sort elements of a Set using Set.shuffled() method.