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

Sorted

While the sort algorithm sorts the array in place (replaces the original array), the sorted algorithm does not change the original array; it instead creates a new array with the sorted elements from the original array. The following example shows how to use the sorted algorithm:

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

After we run this code, arrayOne will contain the original unsorted array (9, 3, 6, 2, 8, and 5) and the sorted array will contain the new sorted array (2, 3, 5, 6, 8, and 9).

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