Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在Swift中对多维数组(数组中的数组)使用排序?_Arrays_Swift_Sorting_Multidimensional Array - Fatal编程技术网

Arrays 在Swift中对多维数组(数组中的数组)使用排序?

Arrays 在Swift中对多维数组(数组中的数组)使用排序?,arrays,swift,sorting,multidimensional-array,Arrays,Swift,Sorting,Multidimensional Array,我想知道如何在Swift中使用多维数组的排序或排序函数 例如,数组: [ [5, "test888"], [3, "test663"], [2, "test443"], [1, "test123"] ] 我想通过第一个ID从低到高进行排序: [ [1, "test123"], [2, "test443"], [3, "test663"], [5, "test888"] ] 那我们怎么做呢?谢谢 您可以使用排序: let sort

我想知道如何在Swift中使用多维数组的
排序
排序
函数

例如,数组:

[
    [5, "test888"],
    [3, "test663"],
    [2, "test443"],
    [1, "test123"]
]
我想通过第一个ID从低到高进行排序:

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

那我们怎么做呢?谢谢

您可以使用
排序

let sortedArray = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }

我认为您应该使用一个元组数组,这样类型转换就不会有任何问题:

let array : [(Int, String)] = [
    (5, "test123"),
    (2, "test443"),
    (3, "test663"),
    (1, "test123")
]

let sortedArray = array.sorted { $0.0 < $1.0 }
let数组:[(Int,String)]=[
(5,“测试123”),
(2,“test443”),
(3,“test663”),
(1,“测试123”)
]
让sortedArray=array.sorted{$0.0<$1.0}
Swift是关于类型安全的


(如果您使用的是Swift 2.0,请将
sorted
更改为
sort

更新Swift 5.0

排序函数重命名为sorted。下面是新语法

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

与Swift 3,4中中的“排序”功能不同,您应该使用“比较”。例如:

let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }

好的,这个代码工作正常。我还想问,我们如何使用sorted对NSDate进行排序(从现在到过去)?:)小心,Swift 3中的情况又发生了变化,
sort
是变异方法,
sorted
是返回新数组的方法。。。
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")]
let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }