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 ""}
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.
sort is 13% faster than sorted .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With