.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.
arrayName.sort() arrayName.sort(by: predicate)
by parameter, the sorting order can be altered.
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"]
Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.
Learn Swift on Codecademy
Build iOS Apps with SwiftUIBy the end of this Skill Path, you will have created your very own fully functional quiz game for iOS devices—and learned Swift too!
Includes 7 Courses