Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
sort
array
communitycreator

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

Theodore Kelechukwu Onyejiaku

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)
Sort array elements using the sort() method

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.

RELATED TAGS

swift
sort
array
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring