如何在Swift 4中对字典数组进行排序 [英] How to sort an array of dictionary in swift 4

查看:151
本文介绍了如何在Swift 4中对字典数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的NSObject类

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

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

The variable I created to store CustomDate

var dates = [CustomDate]()

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

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

例如照片

推荐答案

要按数字顺序比较字符串,请使用localizedStandardCompare(类似于Finder中的排序方式)

To compare strings in numeric order either use localizedStandardCompare which sorts like in 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.


The best solution might be to declare month as Int.

这篇关于如何在Swift 4中对字典数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆