Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between sorted and sort in Array

Tags:

In Swift 3, what is the difference between:

self.myArray.sort(by: { $0.name > $1.name }) 

And

let newSortedArray = self.myArray.sorted(by: { $0.name > $1.name }) 

The effect seems to be the same, but I need to pass the result of the second one to another Array (or to itself?), to be able to use it.

What is the difference? Help is very appreciated.

In this example myArray is an Array of struct Whatever {var name: String ""}

like image 221
David Seek Avatar asked Nov 15 '16 22:11

David Seek


People also ask

What is the difference between sort () and sorted ()?

The primary difference between the two is that list. sort() will sort the list in-place, mutating its indexes and returning None , whereas sorted() will return a new sorted list leaving the original list unchanged.

Is sort () or sorted () faster?

sort is 13% faster than sorted .

What does sorted () do?

The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


1 Answers

sort mutates the array it is called on so its items are sorted. sorted returns a copy of the array it is called on with the values sorted.

If the original order of your array is important, calling sort on it would cause serious problems.

Also, if you have a giant array that contained value types and called sorted on it, it would duplicate each value and double the memory usage.

like image 64
AdamPro13 Avatar answered Oct 12 '22 14:10

AdamPro13