Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 sorting an array of tuples

I found these answers:

Sort an array of tuples in swift 3 How to sort an Array of Tuples?

But I'm still having issues. Here is my code:

var countsForLetter:[(count:Int, letter:Character)] = []
...
countsForLetter.sorted(by: {$0.count < $1.count})

Swift 3 wanted me to add the by: and now it says that the result of the call to sorted:by is unused.

I'm new to swift 3. Sorry if this is a basic question.

like image 269
Thom Avatar asked Mar 03 '17 00:03

Thom


People also ask

How do you sort an array of objects 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 a list 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.

What is difference between tuple and array in Swift?

Both tuples and arrays allow us to hold several values in one variable, but tuples hold a fixed set of things that can't be changed, whereas variable arrays can have items added to them indefinitely.

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.


2 Answers

You are getting that warning because sorted(by... returns a new, sorted version of the array you call it on. So the warning is pointing out the fact that you're not assigning it to a variable or anything. You could say:

countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})

I suspect that you're trying to "sort in place", so in that case you could change sorted(by to sort(by and it would just sort countsForLetter and leave it assigned to the same variable.

like image 81
creeperspeak Avatar answered Oct 13 '22 19:10

creeperspeak


Sorted() returns a new array, it does not sort in place.

you can use :

countsForLetter  = countsForLetter.sorted(by: {$0.count < $1.count})

or

countsForLetter.sort(by: {$0.count < $1.count})
like image 32
Alain T. Avatar answered Oct 13 '22 20:10

Alain T.