Swift排序数组<array <anyobject>&gt;

时间:2016-07-27 05:32:30

标签: swift

我有以下回复。如何根据第一个元素排序。即[["Albania", "AE"], ["United States", "US"]]

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

3 个答案:

答案 0 :(得分:2)

var array = [ [ "United States", "US" ], [ "Albania", "AE" ] ] 
array.sortInPlace({$0[0] < $1[0]})

答案 1 :(得分:1)

使用Closures实现此目的的一种简单方法。

这是一种速记排序方式。

    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)

答案 2 :(得分:0)

尝试

var a = [ [ "United States", "US" ], [ "Albania", "AE" ] ]

a.sort { (first, second) -> Bool in
   return first.first < second.first
}