Search code examples
swift2ios9xcode7

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?


Solution

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