问题
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"})
How do I sort this array by most recent transactionTime? Using Swift4.
Thank you.
Edit: It's easier to have back-end people do it for you.
回答1:
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)
Output
[["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"]]
来源:https://stackoverflow.com/questions/53928563/how-to-sort-an-array-of-nsdictionary-using-datetime-key-swift-4