Arefly Arefly - 2 months ago 5
Swift Question

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!

Answer

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]]
Comments