以swift对收到的回复日期进行排序



我正在编写代码,其中我接收了大量与日期相关的数据每个对象都有一个日期参数,并且可能有许多对象具有相同的日期。

我需要在UITableView中显示所有对象。每个对象作为一个单元。我成功地做到了,我需要从对象的响应数组中获取唯一的日期。这些唯一的日期将存储在一个数组中,该数组将作为我的表视图的多个部分,部分标题将是唯一日期数组中的日期。

不知怎么的,我能够用我想要的东西来解决这个问题,我面临的唯一问题是无法对唯一的日期数组进行排序每次序列改变时。我需要最晚的日期作为第一个日期,最早的日期作为结束日期。

如何在swift中实现这一点。

以下是我写的代码

let sortedKeys = Array(dictValue.keys).sorted(by: {$0 > $1})
print(sortedKeys)

这里dicValue.keys是我唯一的日期数组,我想对它进行排序。

以下是我收到的样本响应

["08/03/2021”, “10/02/2021”,  "26/04/2021", "25/03/2021”,  "09/12/2020”, , "27/04/2021”,  "23/03/2021”,  "11/01/2021”,  "05/03/2021”,  "09/03/2021”, "16/10/2020", "19/03/2021", "12/10/2020" ]

在应用排序后,我得到以下输出

[“27/04/2021", "26/04/2021", "25/03/2021", "23/03/2021", "19/03/2021", "16/10/2020", "12/10/2020", "11/01/2021", "10/02/2021", "09/12/2020", "09/03/2021", "08/03/2021", "05/03/2021”]

日期没有正确排序。谁能帮我一下吗?

提前谢谢。

此字符串日期格式不适合排序,因为最重要的组件是day。只有像yyyy/MM/dd这样的日期格式才能由比较运算符>正确排序。

不过这是斯威夫特。闭包可以包含任何内容,只要它返回Bool即可。您可以使用自定义排序算法对数组进行排序。它将字符串拆分为组件,并首先对yearmonthday 进行排序

let sortedKeys = dictValue.keys.sorted { (date1, date2) -> Bool in
    let comps1 = date1.components(separatedBy: "/")
    let comps2 = date2.components(separatedBy: "/")
    return (comps1[2], comps1[1], comps1[0]) > (comps2[2], comps2[1], comps2[0])
}
print(sortedKeys)

如果要对日期进行排序,只需对Date进行排序。Date支持Hashable,可以用作字典键,您可以映射原始字典,并使用DateFormatter将字符串键格式化为Dates,然后可以轻松地对其进行排序。

let dictionary = ["08/03/2021": 2, "10/02/2021": 5,  "26/04/2021" : 6]
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy" // You should probably adjust other properties of the formatter
let newDict = Dictionary(uniqueKeysWithValues:
                            dictionary.map { (key, value) -> (Date, Int) in
                                print("Key: (key)")
                                return (formatter.date(from: key)!, value)
                            })
let sortedDates = newDict.keys.sorted { $0 > $1 }
let value = newDict[sortedDates[0]]

最新更新