6

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!

4 Answers 4

16

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array...
7

Update for Swift 5.0

sort function is renamed to sorted. Here is the new syntax

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

Unlike "sort" function in <= swift4.0, sort function doesn't modify elements in array. Instead, it just returns a new array.

example,

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")]

Comments

4

I think you should use an array of tuples, then you won't have any problems with type casts:

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

let sortedArray = array.sorted { $0.0 < $1.0 }

Swift is all about type safety

(Change sorted to sort if you're using Swift 2.0)

1 Comment

OK, this code is working fine. And I also want to ask that how can we use sorted to sort NSDate (from present to past) ? :)
0

in Swift 3,4 you should use "Compare". for example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.