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 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 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 JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course