Swift Sort: Quick Swift Cool Tips Sort VS Sorted

The functions that sort an array in swift include sort and sorted. Most developers use only sort or only sorted. I feel sad for them. If you know the difference between the two, you can write more efficient code! I’ll explain in one minute, so listen carefully.

sort

sort sorts the original array in ascending order.

So it is not suitable if you need to have the original array in memory (e.g. you need to sort one array in several ways).

var arr = [1, 2, 5, 4, 6] 
arr.sort()
print(arr) // [1, 2, 4, 5, 6]

Do you want to customize the sort criteria of an array? You can use the sort(by: (Int, Int) throws -> Bool) function.

// sort(by: (Int, Int) throws -> Bool)var arr = [1, 2, 5, 4, 6] 
arr.sort { (a, b) -> Bool in return a < b }
print(arr) // [1, 2, 4, 5, 6]
var arr = [1, 2, 5, 4, 6]
arr.sort { return $0 < $1 } print(arr) // [1, 2, 4, 5, 6]

In this case, when the name of the argument is not needed, it can be expressed concisely as $0, $1.

sorted

sorted leaves the original array as it is, makes a copy, sorts it in ascending order, and returns it.

var arr = [1, 2, 5, 4, 6]
arr.sorted()
print(arr) // [1, 2, 5, 4, 6]
var arr = [1, 2, 5, 4, 6]
var copied = arr.sorted()
print(arr) // [1, 2, 5, 4, 6]
print(copied) // [1, 2, 4, 5, 6]
print(arr.sorted()) // [1, 2, 4, 5, 6]

Because a copy is made, if arr is printed, the unaligned original arr will be printed.

The sorted function can also be customized.

Conclusion

sorted uses double the memory because it makes a copy. Do not use if the size of the array is very large!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!