Swift Sort: Quick Swift Cool Tips Sort VS Sorted

sort

var arr = [1, 2, 5, 4, 6] 
arr.sort()
print(arr) // [1, 2, 4, 5, 6]
// 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]

sorted

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]

Conclusion

--

--

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

KD Knowledge Diet

2.4K Followers

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