我试图在Swift中对一组字典进行排序。我的结构是这样的:
data = new[10];
foreach(data[ii]) data[ii] = $urandom;
我试图按照每个" [
[
"DateTime": "8/16/16, 4:00 PM",
"Owner": "Teacher1",
"Subject": "AP Euro",
"Address": "Mr. Hughes\' Room",
"Type": "Final",
"Timestamp": "2016081616009498",
"Location": "On Campus",
"Duration": "50 min",
"Members": "ownerKey,1,107434,109431"
],
[
"DateTime": "7/29/16, 6:35 AM",
"Owner": "109431",
"Subject": "Algebra 2 Acc",
"Address": "Library",
"Type": "Quiz",
"Timestamp": "2016072906356642",
"Location": "On Campus",
"Duration": "5 min",
"Members": "ownerKey"
]
]
"对数组进行排序。每个字典中的值。我怎么能这样做?
我目前的代码(不工作)是:
Timestamp
答案 0 :(得分:5)
foo.sortInPlace { $0["Timestamp"] < $1["Timestamp"] }
由于timestamp是一个字符串编码的日期,你需要先将它转换为更有用的东西,使用NSDateFormatter是最简单的方法:
这里有很多!
你应该做一些更合适的事情,但这会给你一个基本的想法:
let foo = [
[
"DateTime": "8/16/16, 4:00 PM",
"Owner": "Teacher1",
"Subject": "AP Euro",
"Address": "Mr. Hughes\' Room",
"Type": "Final",
"Timestamp": "2016081616009498",
"Location": "On Campus",
"Duration": "50 min",
"Members": "ownerKey,1,107434,109431"
],
[
"DateTime": "7/29/16, 6:35 AM",
"Owner": "109431",
"Subject": "Algebra 2 Acc",
"Address": "Library",
"Type": "Quiz",
"Timestamp": "2016072906356642",
"Location": "On Campus",
"Duration": "5 min",
"Members": "ownerKey"
]
]
let formatter = NSDateFormatter()
formatter.dateFormat = "M/dd/yy, h:mm a"
let sorted = foo.sort {
formatter.dateFromString($0["DateTime"]!)!.compare(formatter.dateFromString($1["DateTime"]!)!) != .OrderedDescending
}
print("\(sorted)")