Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorted function in Swift 2

I'm sorting an Array like this:

var users = ["John", "Matt", "Mary", "Dani", "Steve"]

func back (s1:String, s2:String) -> Bool
{
    return s1 > s2
}

sorted(users, back)

But I'm getting this error

'sorted' is unavailable: call the 'sort()' method on the collection

What should be the correct way to use the sort() method here?

like image 584
Marcos Reboucas Avatar asked Dec 01 '22 17:12

Marcos Reboucas


1 Answers

Follow what the error message is telling you, and call sort on the collection:

users.sort(back)

Note that in Swift 2, sorted is now sort and the old sort is now sortInPlace, and both are to be called on the array itself (they were previously global functions).

Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array.

like image 108
Eric Aya Avatar answered Dec 10 '22 13:12

Eric Aya