.sort()
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"]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours