by Sai gowtham

How to sort an array of numbers in Swift

Swift has a built-in sort() method by using that we can sort an array both ascending and descending order.

Sort array in ascending order

var numbers = [3,54,1,5,2];

numbers.sort() // sorting

print(numbers)

Output:

[1,2,3,5,54]

Sort array in descending order

To sort an array in descending order we need to pass by: > as an argument to the sort() method.

var numbers = [3,54,1,5,2];

numbers.sort(by: >) // sorting descending order

print(numbers)

Output:

[54,5,3,2,1]

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course