Thripthi Haridas Thripthi Haridas - 4 months ago 22
Swift Question

Swift Sorting Array<Array<AnyObject>>

I have the below response. how to sort according to the first element. i.e.

[["Albania", "AE"], ["United States", "US"]]


[
[
"United States",
"US"
],
[
"Albania",
"AE"
]
]

Answer

One easy way to achieve this using Closures.

Here is a Shorthand way of sorting.

    let array = [["United States","US"],["Albania", "AE"],["India", "IN"],["United Kingdom", "UK"]]
    print(array)

    let arrAscending = array.sort({($0[0]) < ($1[0])})
    let arrDescending = array.sort({($0[0]) > ($1[0])})

    print(arrAscending)
    print(arrDescending)
Comments