Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sort and sortInPlace in swift 2?

Tags:

swift

swift2

I have been trying to use the sortInPlace function in swift but it is not working. When I use the sort function instead of sortinplace it works.

Please explain the difference between these 2 function. It would be very helpful if you can provide small code sample demonstrating the use of both functions.

like image 236
Ankit Goel Avatar asked Nov 07 '15 07:11

Ankit Goel


People also ask

What is the difference between sort and sorted in Swift?

sorted() and sorted(by:) has the same functionality as sort() and sort(by:) . The only difference is that they return the new sorted elements of the sequence instead of modifying the original array.

What is sort in Swift?

In Swift, we can also sort arrays in ascending and descending order. To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order.

How do I sort numbers in Swift?

Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator ( < ). To sort the elements of your collection in descending order, pass the greater-than operator ( > ) to the sort(by:) method. The sorting algorithm is not guaranteed to be stable.


1 Answers

var mutableArray = [19, 7, 8, 45, 34]

// function sort sorts the array but does not change it. Also it has return

mutableArray.sort()

mutableArray
// prints 19, 7, 8, 45, 34

// function sortInPlace will mutate the array. Do not have return

mutableArray.sortInPlace()

mutableArray
// prints 7, 8, 19, 34, 45
like image 187
nadi9 Avatar answered Sep 22 '22 17:09

nadi9