Swift Array Sorting

To sort an Array in Swift, we can call any of the method on the array (mentioned in the following table), based on the sorting behaviour, and inplace sorting.

In this tutorial, we will go through each of these methods with examples.

MethodInplace SortingCondition to Sort
sort()YesImplicit sorting condition
sort(by:)YesExplicit sorting condition provided via by parameter
sorted()NoImplicit sorting condition
sorted(by:)NoExplicit sorting condition provided via by parameter

sort()

sort() method sorts the array in place, meaning the original array is modified.

Example

In the following program, we will take an array of numbers and sort them using sort() method.

main.swift

</>
Copy
var arr = [2, 8, 1, 9, 4, 7]
arr.sort()
print(arr)

Output

Swift Array Sorting using sort() method

sort(by:)

sort(by:) method sorts the array in place using the given predicate as the comparison between elements. In place sorting means, the original array is modified.

Example

In the following program, we will take an array of strings and sort them using sort(by:) method, based on the condition that the string length decides which string is greater.

main.swift

</>
Copy
var ids = ["ab", "qprs", "mno", "vwxyz", "c"]
ids.sort(by: {$0.count < $1.count})
print(ids)

Output

Swift Array Sorting using sort(by:) method

sorted()

sorted() method sorts a new array with the elements of original array sorted. Contents of original array remain unchanged.

Example

In the following program, we will take an array of numbers and sort them using sorted() method.

main.swift

</>
Copy
var ids = [2, 8, 1, 9, 4, 7]
var sortedIds = ids.sorted()
print("Original Array: \(ids)")
print("Sorted   Array: \(sortedIds)")

Output

Swift Array Sorting using sorted() method

sorted(by:)

sorted(by:) method creates a new array with the elements of the original array sorted using the given predicate as the comparison between elements. Original array remain unchanged.

Example

In the following program, we will take an array of strings and sort them using sorted(by:) method, based on the condition that the string length decides which string is greater.

main.swift

</>
Copy
var strArr = ["ab", "qprs", "mno", "vwxyz", "c"]
var sortedArr = strArr.sorted(by: {$0.count < $1.count})
print("Original Array: \(strArr)")
print("Sorted   Array: \(sortedArr)")

Output

Swift Array Sorting using sorted(by:) method

Conclusion

In this Swift Tutorial, we learned how to sort an Array in Swift using different methods like sort(), sort(by:), sorted() and sort(by:).