在Swift中如何对多维数组(数组中包含数组)进行排序?

6

我想知道如何在Swift中对多维数组使用sortsorted函数。

例如,有一个数组:

[
    [5, "test888"],
    [3, "test663"],
    [2, "test443"],
    [1, "test123"]
]

我希望你能够通过第一个ID从低到高对其进行排序:

[
    [1, "test123"],
    [2, "test443"],
    [3, "test663"],
    [5, "test888"]
]

那么我们该如何做呢?谢谢!
4个回答

16
您可以使用sort
let sortedArray = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }

结果:

[[1, test123], [2, test443], [3, test663], [5, test123]]

由于数组内容是AnyObject类型,我们可以选择将参数转换为Int。

注意: 在Swift 1中,sort曾被命名为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
请注意,在Swift 3中,这又发生了变化,其中sort是可变方法,而sorted是返回一个新数组的方法... - Eric Aya

7

Swift 5.0 更新

sort 函数已更名为 sorted。以下是新的语法:

let sortedArray = array.sorted(by: {$0[0] < $1[0] })

与Swift 4.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")]

4
我认为你应该使用元组数组,这样就不会遇到类型转换的问题了:
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)


好的,这段代码运行良好。我还想问一下,我们如何使用 sorted 对 NSDate 进行排序(从现在到过去)? :) - He Yifei 何一非

0
在Swift 3、4中,您应该使用“Compare”。例如:
let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }

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