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

时间:2018-06-14 11:17:13

标签: ios arrays swift dictionary swift4

这是我的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]()

我从6个键值对的字典中获取json的数据我想要的是你可以看到下面的照片是打印日期和月份。但我需要按升序(或降序)对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 个答案:

答案 0 :(得分:5)

要按数字顺序比较字符串,请使用{Finder

中排序的localizedStandardCompare
dates.sort(by: {$0.month.localizedStandardCompare($1.month) == .orderedAscending})
带有选项compare

numeric

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

最佳解决方案可能是将month声明为Int

答案 1 :(得分:2)

您可以按此对自定义数组进行排序。 排序是用于对自定义数组进行排序的高阶函数之一。

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