我有一个Array
:var messageArray = [AnyObject]()
,Array
中有一个元组,其中包含Dictionaries
个10个键/值对(其中9个不重要)排序):var messageDetailDict = [String: AnyObject]()
获取和设置这些值都可以正常工作,但现在我想按Array
的值(而不是键)对Dictionary
进行排序。
示例 - > Array
的元组包含多个Dictionaries
:
Dictionary
(Array
中的第一个元素)中的键是:' ReceivedAt'其值为21-03-2015
Dictionary
中的密钥(Array
中的第二个元素)是:' ReceivedAt'其值为20-03-2015
Dictionary
中的密钥(Array
中的第三个元素)是:' ReceivedAt'其值为15-03-2015
现在应该对Array
进行排序,以便“接收到”的值为“{1}}。将从最早的日期到最后的日期排序。
希望这是有道理的,但有点难以解释。谢谢!
编辑>>>>>
这是println(messageArray)
输出:
[(
{
ConversationId = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
Data = "Hello World";
Id = "eeb5ac08-209f-4ef0-894a-72e77f01b80b";
NeedsPush = 0;
ReceivedAt = "/Date(1439920899537)/";
SendAt = "/Date(1436620515000)/";
Status = 0;
},
{
ConversationId = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
Data = "Hello World";
Id = "86b8766d-e4b2-4ef6-9112-ba9193048d9d";
NeedsPush = 0;
ReceivedAt = "/Date(1439921562909)/";
SendAt = "/Date(1436620515000)/";
Status = 0;
}
)]
使用以下方法将收到的日期转换为字符串(我确实认为这不重要,因为它是一个时间间隔,因此可以排序):
func getTimeStampFromAPIValue(dateTimeReceived: String) -> String {
let newStartIndex = advance(dateTimeReceived.startIndex, 6)
let newEndIndex = advance(dateTimeReceived.endIndex, -2)
let substring = dateTimeReceived.substringWithRange(newStartIndex..<newEndIndex) // ell
let receivedAtValueInInteger = (substring as NSString).doubleValue
let receivedAtValueInDate = NSDate(timeIntervalSince1970:receivedAtValueInInteger/1000)
//format date
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yy hh:mm"
var dateString = dateFormatter.stringFromDate(receivedAtValueInDate)
return dateString
}
答案 0 :(得分:3)
由于ReceivedAt
的值是时间戳作为字符串,您可以应用以下算法:
var sortedArray = messageArray.sorted { (dict1, dict2) in
// Get the ReceivedAt value as strings
if let date1String = dict1["ReceivedAt"] as? String,
let date2String = dict2["ReceivedAt"] as? String {
// Compare the date strings to find the earlier of the two
return date1String.compare(date2String) == .OrderedAscending
}
// Couldn't parse the date, make an assumption about the order
return true
}
答案 1 :(得分:-1)
尝试此操作,如果需要按相反的顺序更改OrderedAscending
OrderedDescending
messageArray.sortInPlace {
($0["ReceivedAt"] as! NSDate).compare($1["ReceivedAt"] as! NSDate) == .OrderedAscending
}