按特定键排序字典数组

时间:2015-11-29 19:19:54

标签: ios arrays sorting dictionary swift2

我有一个字典数组,我试图通过字典的特定键对整个数组进行排序,例如根据下面的例子的价格值。 Swift 2.0中是否有任何排序功能,还是我应该自己编写?

"data": [
{
  "id": 932,
  "name": "x product",
  "price": "84.00",
},
{
  "id": 173,
  "name": "z product",
  "price": "69.00",
},
{
  "id": 818,
  "name": "y product",
  "price": "155.00",
},

3 个答案:

答案 0 :(得分:3)

您可以使用 sortInPlace 方法在Swift中进行排序:

data!.sortInPlace({$1["price"] as! Int > $0["price"] as! Int}) 

答案 1 :(得分:1)

您可以使用 NSSortDescriptor

let sortDescriptor = NSSortDescriptor(key: "price", ascending: true)
yourArray = yourArray.sortedArrayUsingDescriptors([sortDescriptor])

适用于Swift 3.0

let sortDescriptor = NSSortDescriptor(key: "price", ascending: true)
yourArray = yourArray.sortedArray(using: [sortDescriptor]) as NSArray

yourArrayNSArray

的位置

答案 2 :(得分:0)

此处描述的两种解决方案都会自动放弃price不可用或不是有效Double值的值。

解决方案1:结构化方法

<强>模型

struct Item: Comparable {
    let id: Int
    let name: String
    let price: Double

    init?(dict: [String:Any]) {
        guard let
            id = dict["id"] as? Int,
            name = dict["name"] as? String,
            priceString = dict["price"] as? String,
            price = Double(priceString) else {
                return nil
        }
        self.id = id
        self.name = name
        self.price = price
    }
}

func <(left: Item, right: Item) -> Bool {
    return left.price < right.price
}

func ==(left: Item, right: Item) -> Bool {
    return left.price == right.price
}

数据

var data : [[String:Any]] = [
    ["id": 932, "name": "x product", "price": "84.00"],
    ["id": 173, "name": "z product", "price": "69.00"],
    ["id": 818, "name": "y product", "price": "155.00"]
]

<强>分拣

let sortedItems = data.flatMap { Item(dict: $0) }.sort()

解决方案2:非结构化方法

let sortedData = data.flatMap { (dict:[String : Any]) -> (dict:[String : Any], price: Double)? in
    guard let
        priceString = dict["price"] as? String,
        price = Double(priceString) else { return nil }
    return (dict, price) }
    .sort { $0.1 < $1.1 }
    .map { $0.dict }