Related Tags

set
sort
descending
communitycreator

# How to sort a set in descending order in Swift

Theodore Kelechukwu Onyejiaku

### Overview

In Swift, the sorted(by:) method is used to sort a set in descending order. The > operator is used alongside this method. We pass the greater-than operator to this method as a parameter.

Note: In Swift, a set is a sequence of unique elements.

### Syntax

set.sorted(by: >)
Syntax for the sorting a set using the > operator

### Parameters

This method takes a parameter, >, which represents the greater-than operator. With this, we can sort the elements of a set.

### Return value

It returns a set of elements that are sorted in descending order.

### Example

// create a set
var workers: Set = ["Alicia", "Bethany", "Diana"]
var randomNumbers: Set = [22, 12, 100, 4, 35, 1, 2, 9, 90]

// get sets sorted in descending order
let descendingWorkers = workers.sorted(by: >)
let descendingNumbers = randomNumbers.sorted(by: >)

// print sorted sets
print(descendingWorkers)
print(descendingNumbers)
Sort elements of a set in descending order using the > operator

### Explanation

• Line 2 and 3: We create two set variables and initialize them.
• Line 6 and 7: With the sorted(by:) method, we sort the sets using the > operator as a parameter. This way, the sets get sorted in descending order. We then store the results to some variables.
• Line 10 and 11: We print the results to the console.

RELATED TAGS

set
sort
descending
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time