O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sort

The sort algorithm sorts an array in place. This means that, when the sort() method is used, the original array is replaced with the sorted one. The closure takes two arguments (represented by $0 and $1), and it should return a Boolean value that indicates whether the first element should be placed before the second element. The following code shows how to use the sort algorithm:

var arrayOne = [9,3,6,2,8,5]arrayOne.sort(){ $0 < $1 } 
//arrayOne contains 2,3,5,6,8 and 9 

The preceding code will sort the array in ascending order. We can tell this because the rule will return true if the first number ($0) is less than the second number ($1). Therefore, when the sort algorithm begins, it compares the first two numbers (9 and 3) and returns ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required