【问题标题】:Sorting array of dictionaries by specific key按特定键对字典数组进行排序
【发布时间】:2016-03-03 09:37:02
【问题描述】:

我有一个字典数组,我正在尝试按字典的特定键对整个数组进行排序,例如根据以下示例的价格值。 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",
},

【问题讨论】:

    标签: ios arrays sorting dictionary swift2


    【解决方案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

    【讨论】:

    • 我更新了我的代码如下,它工作了,感谢 Rajan;
    • 让 priceSortDescriptor = NSSortDescriptor(key: "pPrice", ascending: true) let sortedByPrice = (products as AnyObject).sortedArrayUsingDescriptors([priceSortDescriptor])
    • @mehmeet43 如果它适合您,请接受我提供的通用方法。谢谢
    【解决方案2】:

    此处描述的两种解决方案都会自动丢弃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 }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-27
        • 2016-04-17
        • 1970-01-01
        • 2018-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多