How to sort an array of dictionary in swift 4

后端 未结 2 1650
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 06:27

This is my NSObject class

class CustomDate: NSObject {
    var quarter: Int!
    var day: String!
    var month: String!
    var db: String!
    var long: String         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 06:50

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

提交回复
热议问题