How to sort elements of an array using the sort() method in Swift

Overview

In Swift, the sort() method of an array is used to sort elements of the array.

Syntax

array.sort()

Parameters

This method has no parameters.

Return value

It sorts the elements of the array in an ascending order.

Example

// create arrays
var arr1 = [34, 4, 2, 1]
var arr2 = ["e", "c", "d", "a", "b"]
// sort arrays
arr1.sort()
arr2.sort()
// print results
print(arr1)
print(arr2)

Explanation

  • Line 2 and 3: We create arrays.
  • Line 6 and 7: We invoke the sort() method on the arrays.
  • Line 10 and 11: We print the sorted arrays to the console.

Free Resources