I want to know that how can we use sort
or sorted
function for multidimensional array in Swift?
For example theirs an array:
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)
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]]
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")]
in Swift 3,4 you should use "Compare". for example:
let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }