我想知道我们如何在Swift中使用sort
或sorted
函数用于多维数组?
例如他们的数组:
[
[5, "test888"],
[3, "test663"],
[2, "test443"],
[1, "test123"]
]
我希望通过第一个ID从低到高排序:
[
[1, "test123"],
[2, "test443"],
[3, "test663"],
[5, "test888"]
]
那我们怎么做呢?谢谢!
答案 0 :(得分:6)
您可以使用sort
:
let sortedArray = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
结果:
[[1,test123],[2,test443],[3,test663],[5,test123]]
我们可选择将参数转换为Int,因为数组的内容是AnyObject。
注意:sort
以前在Swift 1中被命名为sorted
。
如果将内部数组声明为AnyObject没有问题,空的数组不会被推断为NSArray:
var arr = [[AnyObject]]()
let sortedArray1 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
print(sortedArray1) // []
arr = [[5, "test123"], [2, "test443"], [3, "test663"], [1, "test123"]]
let sortedArray2 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
print(sortedArray2) // [[1, test123], [2, test443], [3, test663], [5, test123]]
答案 1 :(得分:3)
我认为你应该使用一组元组,然后你就不会有类型转换的任何问题:
let array : [(Int, String)] = [
(5, "test123"),
(2, "test443"),
(3, "test663"),
(1, "test123")
]
let sortedArray = array.sorted { $0.0 < $1.0 }
Swift完全是关于类型安全的
(如果您使用的是Swift 2.0,请将sorted
更改为sort
答案 2 :(得分:0)
针对Swift 5.0的更新
sort函数被重命名为sorted。这是新语法
let sortedArray = array.sorted(by: {$0[0] < $1[0] })
与<= swift4.0中的“ sort”函数不同,sort函数不会修改数组中的元素。而是返回一个新数组。
示例
let array : [(Int, String)] = [
(5, "test123"),
(2, "test443"),
(3, "test663"),
(1, "test123")
]
let sorted = array.sorted(by: {$0.0 < $1.0})
print(sorted)
print(array)
Output:
[(1, "test123"), (2, "test443"), (3, "test663"), (5, "test123")]
[(5, "test123"), (2, "test443"), (3, "test663"), (1, "test123")]
答案 3 :(得分:0)
在Swift 3,4中,您应该使用“比较”。例如:
let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }