Ad space (banner)
๐ŸฆSwift Lessons
Lesson 11 / 68

Sorting an Array

In this lesson you will learn how to sort an array in Swift, a basic operation you will use constantly in practice. This is for anyone searching for "Swift array sort how to use".

.sort() reorders an array in place. Swift arrays come with a great many handy methods.

The sample code sorts an array of integers into ascending order with nums.sort(). There is also sorted, which leaves the original untouched and returns a new array, and you pick to suit the job.

A common stumbling block for beginners is the difference between sort() and sorted(). sort() rewrites the original array while sorted() returns a new one, and missing that leads to behaviour you did not intend.

In real-world development, sorting by your own comparison rule is also common, giving you flexible ordering to suit the purpose.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)