0
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}
var reversed = names.sort(backwards)
print(reversed)
var ascending = names.sort({ (s1: String, s2: String) -> Bool in
    return s1 < s2
})
print(ascending)
let sortAscending = { (s1: String, s2: String) -> Bool in
    return s1 < s2
}
ascending = names.sort(sortAscending)

I am suppose to sort this code according to the number of characters they have from the most to the least. For example, Daniella has 8 characters so she will be fist in the list. The output I am suppose to get is ["Daniella", "Barry", "Chris", "Alex", "Ewa"]

5
  • Hey man, you might also want to check our sort vs sorted discussion below — I don't think your code compiles at all :( Commented Apr 28, 2017 at 2:32
  • i used var sorted = ascending.sort { $0.characters.count > $1.characters.count } and it works Commented Apr 28, 2017 at 2:42
  • You meant sorted, right? Commented Apr 28, 2017 at 2:45
  • when I used sorted I got an error but no errors for sort Commented Apr 28, 2017 at 2:51
  • @LeoDabus ...not okay: he is using sort and expecting a return value, makes no sense, even when in-place sorting mutable collections. BTW, does Swift returns an empty tuple (aka, Void) in such scenarios? That would explain why his code compiles... Commented Apr 28, 2017 at 2:58

1 Answer 1

1

Try this:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let sortedNames = names.sorted { $0.characters.count > $1.characters.count }
print(sortedNames)

Should I sort or should I sorted? Use sort to order the original array in-place, if declared as a var; if let your code won't even compile. Use sorted to leave your original array alone and return a new, properly sorted array; works on let and var.

Sign up to request clarification or add additional context in comments.

7 Comments

names is immutable. You need to use sortedmethod
I know :) Was thinking about a good name for the sorted array, but gave up haha...
He means that you need to call names.sorted instead of names.sort. I don't think your current code compiles.
He could use sort also but he would need to declare the array as variable
ok thanks! to get my output i just have to replace names with ascending.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.