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.
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.
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.
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.
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
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