Swift 2 中的排序函数

sorted function in Swift 2

我正在像这样对数组进行排序:

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

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

sorted(users, back)

但是我收到了这个错误

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

这里sort()方法的正确使用方法应该是什么?

按照错误消息告诉您的内容进行操作,然后在集合上调用 sort

users.sort(back)

请注意,在 Swift 2 中,sorted 现在是 sort,旧的 sort 现在是 sortInPlace,两者都将在数组本身上调用(它们以前是全局函数)。

注意,这在Swift 3中又变了,其中sort是变异方法,sorted 是返回一个新数组的那个。

另一种方法是简单地使用闭包:

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

另一种使用闭包的方法是:

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


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

    return first < second
})

swift 2.2中,我们可以通过多种方式使用带排序功能的闭包,如下所示。

考虑数组

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

使用 swift 闭包对数组进行排序的不同选项已添加

选项 1

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

选项 2

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

选项 3

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

选项 4

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

选项 5

这是在排序函数中使用闭包最简单的方法。

// With Operator Functions
names = names.sort(>)
print(names)
var array = [1, 5, 3, 2, 4] 

Swift 2.3

let sortedArray = array.sort()

Swift 3.0

let sortedArray = array.sorted()