sorted function in Swift 2

2020-02-12 12:21发布

问题:

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?

回答1:

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.



回答2:

Another way to use closure is:

var numbers = [2,4,34,6,33,1,67,20]


var numbersSorted = numbers.sort( { (first, second ) -> Bool in

    return first < second
})


回答3:

Another way is to use closure in a simple way:

users.sort({a, b in a > b})


回答4:

In swift 2.2 there are multiple ways we can use closures with sort function as follows.

Consider the array

var names:[String] = ["aaa", "ddd", "rrr", "bbb"];

The different options for sorting the array with swift closures are as added

Option 1

// In line with default closure format.
names = names.sort( { (s1: String, s2: String) -> Bool in return s1 < s2 })
print(names)

Option 2

// Omitted args types
names = names.sort( { s1, s2 in return s1 > s2 } )
print(names)

Option 3

// Omitted args types and return keyword as well
names = names.sort( { s1, s2 in s1 < s2 } )
print(names)

Option 4

// Shorthand Argument Names(with $ symbol)
// Omitted the arguments area completely.
names = names.sort( { $0 < $1 } )
print(names)

Option 5

This is the most simple way to use closure in sort function.

// With Operator Functions
names = names.sort(>)
print(names)


回答5:

var array = [1, 5, 3, 2, 4] 

Swift 2.3

let sortedArray = array.sort()

Swift 3.0

let sortedArray = array.sorted()