Swift 3对元组数组进行排序

11

我找到了这些答案:

如何在Swift 3中对元组数组进行排序 如何对元组数组进行排序?

但我仍然遇到了问题。这是我的代码:

var countsForLetter:[(count:Int, letter:Character)] = []
...
countsForLetter.sorted(by: {$0.count < $1.count})

在Swift 3中,它要求我添加“by:”并且现在说调用sorted:by的结果未被使用。

我对Swift 3不熟悉,如果这是一个基本问题,请见谅。

2个回答

24

你之所以收到这个警告是因为 sorted(by... 会返回一个已排序的新数组,而你没有将其赋值给变量或其他任何东西。这个警告是在指出这个事实。你可以这样写:

You are getting that warning because sorted(by... returns a new, sorted version of the array you call it on. So the warning is pointing out the fact that you're not assigning it to a variable or anything. You could say:

countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})

我猜测你想要进行“原地排序”,在这种情况下,你可以将 sorted(by 改为 sort(by ,并且它会仅对 countsForLetter 进行排序,并且保持分配给同一变量。


8

Sorted()方法返回一个新的数组,它不会就地排序。

你可以使用以下方式:

countsForLetter  = countsForLetter.sorted(by: {$0.count < $1.count})

或者
countsForLetter.sort(by: {$0.count < $1.count})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接