Sorting array in Ascending and Descending order in Swift

Swift code to sort an array in Ascending and Descending order. It can be done with the help of sort() method.

Source code :

// Create an unsorted array
var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order


//Sorting Strings

var fruits = ["Orange","Mango","Apple","Banana"]

print(fruits.sort())

Output :

[6, 8, 43, 45, 56, 56, 78, 113]
[113, 78, 56, 56, 45, 43, 8, 6]
["Apple", "Banana", "Mango", "Orange"]

Notes :

Sorting can be done in swift by using the sort() method. Calling the sort() method will sort the array in Ascending order by default.

To sort the array in descending order you have to pass the greater than symbol as a parameter sort(>). It will sort the array in descending order.


Output :


                

Comments :