如何使用DateTime键(Swift 4)对NSDictionary数组进行排序?

时间:2018-12-26 07:01:55

标签: arrays swift sorting nsdictionary

我有一个NSDictionary的NSArray

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。

谢谢。

编辑:让后端人员为您完成这项工作更容易。

1 个答案:

答案 0 :(得分:2)

直到将其转换为Date对象后,您才能进行操作。您可以使用枚举块,并在运行时将字符串转换为date对象,如下例所示:

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)

输出

  

[[“ transactionTime”:“ 04-02-2020 18:32:21”,“ name”:“ Aida”,“ age”:“ 22”],[“ transactionTime”:“ 02-02-2013 10:32:41“,” name“:” Atiqah“,” age“:” 23“],[” transactionTime“:” 01-02-2011 12:32:39“,” name“:” Auni“, “ age”:“ 24”]]