David Seek David Seek - 22 days ago 6
Swift Question

What's the difference between sorted and sort in Array

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 ""}

Answer

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.