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