.sort()

Christine_Yang's avatar
Published Oct 11, 2022
Contribute to Docs

The .sort() method is called on any mutable collection and returns its elements sorted in ascending order by default. This means that the element at index zero is less than (<) that at index one, the elements at index one is < that at index two, and so on.

Syntax

arrayName.sort()

arrayName.sort(by: predicate)

Using the by parameter, the sorting order can be altered.

Example

var topBabyNames = ["Sophia", "Liam", "Riley", "Jackson", "Olivia", "Noah"]
topBabyNames.sort()
print(topBabyNames)
topBabyNames.sort(by: >)
print(topBabyNames)

In the example above, the topBabyNames array is first sorted in ascending order. Then, the greater-than operator, >, is passed as the predicate, which will result in the array being sorted in descending order. This will output:

["Jackson", "Liam", "Noah", "Olivia", "Riley", "Sophia"]
["Sophia", "Riley", "Olivia", "Noah", "Liam", "Jackson"]

All contributors

Contribute to Docs

Learn Swift on Codecademy