The sort() method sorts the items of an array in a specific order (ascending or descending).
Example
var numbers = [1, 3, 8, 5, 2]
// sort the numbers array
numbers.sort()
print(numbers)
// Output: [1, 2, 3, 5, 8]
sort() Syntax
The syntax of the array sort() method is:
array.sort(by: operator)
Here, array is an object of the Array class.
sort() Parameters
The sort() method can take one parameter:
- operator (optional) - If we pass greater-than operator
>, the sorted array is reversed (or sorted in Descending order)
sort() Return Value
The sort() method doesn't return any value. Rather, it changes the order of the original array.
Example 1: Swift Array sort()
// array of strings
var names = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben"]
// sort the names array
names.sort()
print(names)
// array of integers
var priceList = [1000, 50, 2, 7, 14]
// sort the priceList array
priceList.sort()
print(priceList)
Output
["Adam", "Ben", "Danil", "Fabiano", "Jeffrey"] [2, 7, 14, 50, 1000]
Here, we can see that the names array is sorted in ascending order of the string. For example, "Adam" comes before "Danil" because "A" comes before "D".
Similarly, the priceList array is sorted in ascending order.
Example 2: Sorting in Descending Order
// array of strings
var names = ["Adam", "Jeffrey", "Fabiano", "Danil", "Ben"]
// sort the names array
names.sort(by: >)
print(names)
// array of integers
var priceList = [1000, 50, 2, 7, 14]
// sort the priceList array
priceList.sort(by: >)
print(priceList)
Output
["Jeffrey", "Fabiano", "Danil", "Ben", "Adam"] [1000, 50, 14, 7, 2]
Here, to sort the elements in descending order, we have passed the > operator to the sort() method
Note: We can also pass the < operator to sort the elements in ascending order. However, if we do not pass any arguments, the sort() method will arrange the elements in ascending order by default.