How to sort an array of dictionary in swift 4

2020-04-15 11:52发布

问题:

This is my NSObject class

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
    }
}

The variable I created to store CustomDate

var dates = [CustomDate]()

I am getting the data from json in a dictionary in 6 key value pairs what I want is as you can see the photo below is printing the date and month. But I need to sort json data in ascending order(or descending order). How can I do that here is my code. I am using alamofire to getting the data and I create a NSObject class to store data

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
        }
    }
}

Photo for example

回答1:

To compare strings in numeric order either use localizedStandardCompare which sorts like in Finder

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

or compare with option numeric

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

The best solution might be to declare month as Int.



回答2:

You can sort your custom array by this. The sort is one of the High order function which used to sort custom array.

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
        }
    }
}