[英]Sorting array of dictionaries of strings in Swift
I'm trying to sort an array of dictionaries in Swift. 我正在尝试对Swift中的字典进行排序。 My structure is like this:
我的结构是这样的:
[
[
"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"
]
]
I'm trying to sort the array by each " Timestamp
" value in each dictionary. 我正在尝试通过每个字典中的每个“
Timestamp
”值对数组进行排序。 How can I do this? 我怎样才能做到这一点?
My current code (not working) is: 我当前的代码(不起作用)是:
self.todayArray.sortInPlace {item1,item2 in
let date1 = Int("\(item1["Timestamp"])")
let date2 = Int("\(item2["Timestamp"])")
return date1 > date2
}
N/M all the stuff below, it's to sort by the DateTime field, you're trying to sort on the Timestamp field which is already lexicographically sorted, so just use: N / M下面的所有内容,都是按DateTime字段进行排序,您正尝试对已经按字典顺序进行排序的Timestamp字段进行排序,因此只需使用:
foo.sortInPlace { $0["Timestamp"] < $1["Timestamp"] }
Since timestamp is an string-encoded date, you'll need to convert it to something more useful first, using an NSDateFormatter is the easiest way: 由于时间戳是一个字符串编码的日期,因此您首先需要将其转换为更有用的日期,使用NSDateFormatter是最简单的方法:
There's a lot of !
有很多
!
in here that you should do something more appropriate with, but this gives you the basic idea: 在这里您应该做一些更合适的事情,但这给了您基本的思想:
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)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.