To sort the items of a set in Swift, you can convert the set to an array and then sort the array using the sorted()
method.
In this example,
numbers
containing some integer elements using the Set
class.Array
initializer.sorted()
method.let numbers: Set<Int> = [5, 3, 1, 4, 2]
let sortedNumbers = numbers.sorted()
print("Sorted numbers:")
for number in sortedNumbers {
print(number)
}
Sorted numbers: 1 2 3 4 5
In this example,
fruits
containing some string elements using the Set
class.Array
initializer.sorted()
method.let fruits: Set<String> = ["Banana", "Apple", "Cherry", "Date"]
let sortedFruits = fruits.sorted()
print("Sorted fruits:")
for fruit in sortedFruits {
print(fruit)
}
Sorted fruits: Apple Banana Cherry Date
In this tutorial, we learned How to Sort Items of a Set in Swift language with well detailed examples.