Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sort for multidimensional array (array in array) in Swift?

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

For example theirs an array:

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

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!

like image 895
He Yifei 何一非 Avatar asked Nov 30 '22 00:11

He Yifei 何一非


1 Answers

You can use sort:

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

Result:

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

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

Note: sort was previously named sorted in Swift 1.


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]]
like image 62
Eric Aya Avatar answered Dec 05 '22 18:12

Eric Aya