Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
swift
ascending
ascending order
communitycreator

How to sort a set using sorted() and the < operator in Swift

Theodore Kelechukwu Onyejiaku

Overview

In Swift, the sorted() method is used to sort a set in ascending orderAscending order means the elements of a set will begin with the smallest value in number or character and so on. The less-than operator, <, 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 sets
var workers: Set = ["Evangeline", "CHiwendu", "Amara", "Bethany", "Diana"]
var randomNumbers: Set = [12, 1, 45, 6, 90, 102, 88]

// sort them using the sorted() and the < operator
let sortedWorkers = workers.sorted()
let sortedNumbers = randomNumbers.sorted(by: <)

// print sorted sets
print(sortedWorkers)
print(sortedNumbers)
Sort elements of a set in ascending order

Explanation

  • Line 2–3: We create two sets and initialize them.
  • Line 6: We sort the workers set using the sorted() method.
  • Line 7: We sort the set, randomNumbers, using the sorted(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.

RELATED TAGS

set
swift
ascending
ascending order
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring