代码之家  ›  专栏  ›  技术社区  ›  viper

如何在swift 4中对字典数组进行排序

  •  2
  • viper  · 技术社区  · 7 年前

    这是我的nsobject类

    class CustomDate: NSObject {
        var quarter: Int!
        var day: String!
        var month: String!
        var db: String!
        var long: String!
        var unix: Int!
    
        init(quarter: Int, day: String, month: String, db: String, long: String, unix: Int) {
            super.init()
    
            self.quarter = quarter
            self.day = day
            self.month = month
            self.db = db
            self.long = long
            self.unix = unix
        }
    }
    

    我创建的用于存储customdate的变量

    var dates = [CustomDate]()
    

    我从一个字典中的json获取6个键值对的数据,我想要的是你可以看到下面的照片打印日期和月份。但我需要按升序(或降序)对json数据进行排序。这是我的代码。我使用alamofire来获取数据,并创建一个nsobject类来存储数据

    func apiData() {
        Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
    
            switch(response.result) {
            case .success(_):
                guard let json = response.result.value as? [String: Any] else { return }
                guard let data = json["data"] as? [String: Any] else { return }
    
                for (_, value) in data {
                    let dateValue = value as! [String: Any]
                    let date = CustomDate(quarter: dateValue["quarter"] as! Int,
                                          day: dateValue["day"] as! String,
                                          month: dateValue["month"] as! String,
                                          db: dateValue["db"] as! String,
                                          long: dateValue["long"] as! String,
                                          unix: dateValue["unix"] as! Int)
    
                    self.dates.append(date)
                }
                print(self.dates)
                break
            case .failure(_):
                print(response.result.error as Any)
                break
            }
        }
    }
    

    例如照片

    2 回复  |  直到 7 年前
        1
  •  5
  •   vadian    7 年前

    要按数字顺序比较字符串,请使用 localizedStandardCompare 有点像在finder中

    dates.sort(by: {$0.month.localizedStandardCompare($1.month) == .orderedAscending})
    

    compare 有选择权 numeric

    dates.sort(by: {$0.month.compare($1.month, options: .numeric) == .orderedAscending})
    

    最好的解决办法可能是 month 作为 Int .

        2
  •  2
  •   Chirag Shah    7 年前

    您可以按此对自定义数组进行排序。这个 分类 高阶 用于对自定义数组排序的函数。

    func apiData() {
    
        Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
    
            switch(response.result) {
            case .success(_):
                guard let json = response.result.value as? [String: Any] else { return }
                guard let data = json["data"] as? [String: Any] else { return }
    
                for (_, value) in data {
                    let dateValue = value as! [String: Any]
                    let date = CustomDate(quarter: dateValue["quarter"] as! Int,
                                          day: dateValue["day"] as! String,
                                          month: dateValue["month"] as! String,
                                          db: dateValue["db"] as! String,
                                          long: dateValue["long"] as! String,
                                          unix: dateValue["unix"] as! Int)
    
                    self.dates.append(date)
                }
                print("unsorted array \(self.dates.map({$0.month})))")
                self.dates = self.dates.sorted(by: { (objModel, objModel1) -> Bool in return
                    (Int(objModel.month ?? "0") ?? 0) < (Int(objModel1.month ?? "0") ?? 0)
                })
                print("sorted array \(self.dates.map({$0.month}))")
                break
            case .failure(_):
                print(response.result.error as Any)
                break
            }
        }
    }
    

    enter image description here