关于swift:如何有效地按相反顺序对对象数组进行排序?

How do I sort an array of objects in reverse order efficiently?

假设我有一系列字典:

1
[ {"id": 2 }, {"id": 59 }, {"id": 31 } ... ]

我如何排序,使其按降序排列,由"ID"排序?

我最初的方法是:

1
Loop through each element, find the biggest one, and put it into a new array. Then, remove that from the element. Repeat.

但我知道这是错误的,而且效率不高。


您可以在swift中使用排序功能。像这样:

1
2
let arr = [["id": 2], ["id": 59], ["id": 31]]
let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }


您只需要使用下面的代码就可以使用sort给您排序数组,因为dictionary也是一个集合类。

1
2
let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") //

在上面的代码中,您找到了已排序的字典。对于排序数组,需要添加以下代码。

1
let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
    var val = [ {"id": 2 }, {"id": 59 }, {"id": 31 }];
var a = new Array();


for (i = 0; i < val.length; i++) {
    document.write(Object.keys(val[i]).map(function (key) {return val[i][key]})+"");
    a.push(Object.keys(val[i]).map(function (key) {return val[i][key]}));
}
a.sort();

var result = new Array();
for (i = 0; i < val.length; i++) {
result.push({"id": a[i]});
}

我不知道这是最快的还是更好的,但是Swift提供了以clojure为论据的sort方法。你可以这样写:

1
2
3
var ordered = arrdict.sort { (dic1, dic2) -> Bool in
    dic1["id"] > dic2["id"]
}

或紧凑:

1
var ordered = arrdict.sort { $0["id"] > $1["id"] }

$0..x可以访问clojure参数。关于sort算法苹果写:

Discussion The sorting algorithm is not stable (can change the
relative order of elements that compare equal).

Requires: The less-than operator (func <) defined in the Comparable conformance is a strict weak ordering over the elements in self.