本文介绍了如何使用DateTime键(Swift 4)对NSDictionary数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSDictionary的NSArray

I have an NSArray of NSDictionary

let Array = (
{ name = "Auni";
  age = "24";
  transactionTime = "01-02-2011 12:32:39" },
{ name = "Atiqah";
  age = "23";
  transactionTime = "02-02-2013 10:32:41" },
{ name = "Aida";
  age = "22";
  transactionTime = "04-02-2020 18:32:21"})

如何按最近的transactionTime排序此数组?使用Swift4.

How do I sort this array by most recent transactionTime? Using Swift4.

谢谢.

让后端人员为您完成这项工作更容易.

It's easier to have back-end people do it for you.

推荐答案

您不需要转换为Date对象,dateStrings直接比较也将起作用.

You do not need to convert into Date object, dateStrings direct comparison will also work.

array.sort { (dict1, dict2) -> Bool in

    /// Considering "transactionTime" key always exists.
    let transactionTime1 = dict1["transactionTime"]!
    let transactionTime2 = dict2["transactionTime"]!

    /// Sort in descending order
    return transactionTime1 > transactionTime2
}

如果需要对日期对象进行一些计算,则还可以在运行时将字符串转换为日期对象,如下例所示:

In case you need some calculation on date objects then You can also convert the string into date objects at run time like below example:

let df = DateFormatter()
df.dateFormat = "dd-MM-yyyy HH:mm:ss"
array.sort { (dict1, dict2) -> Bool in

    /// Considering "transactionTime" key always exists.
    let transactionTime1 = dict1["transactionTime"]!
    let transactionTime2 = dict2["transactionTime"]!

    let date1 = df.date(from: transactionTime1)!
    let date2 = df.date(from: transactionTime2)!

    /// Sort in descending order
    return date1 > date2
}

print(array)

输出

这篇关于如何使用DateTime键(Swift 4)对NSDictionary数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 09:12