在Swift中对多维数组(数组中的数组)使用sort? [英] Use sort for multidimensional array (array in array) in Swift?

查看:342
本文介绍了在Swift中对多维数组(数组中的数组)使用sort?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to know that how can we use sort or sorted function for multidimensional array in Swift?

例如,他们的数组:

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

我想通过第一个ID的高低对它进行排序:

And I want to sort it via the first ID's low to high:

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

那么我们该怎么做呢?谢谢!

So how can we do this? Thanks!

推荐答案

您可以使用sort:

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

结果:

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

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

由于数组的内容是AnyObject,因此我们可以选择将参数强制转换为Int.

We optionally cast the parameter as an Int since the content of your arrays are AnyObject.

注意:sort在Swift 1中以前被命名为sorted.

Note: sort was previously named sorted in Swift 1.

如果将内部数组声明为AnyObject没问题,那么不会将一个空数组作为NSArray推论:

No problem if you declare the internal arrays as AnyObject, an empty one won't be inferred as an 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]]

这篇关于在Swift中对多维数组(数组中的数组)使用sort?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆