我有一系列字典,他们看起来像这样:
{
Place = "here";
Type = Any;
timeRegisted = "04-24-2017 10:42";
},
{
Place = "there";
Type = Any;
timeRegisted = "04-24-2017 09:52";
},
{
Place = "overThere";
Type = Any;
timeRegisted = "04-24-2017 05:55";
},
{
Place = "somewhere";
Type = Any;
timeRegisted = "04-24-2017 06:15";
},
{
Place = "here";
Type = Any;
timeRegisted = "04-24-2017 06:15";
},
{
Place = "overthere";
Type = Any;
timeRegisted = "04-24-2017 05:42";
},
但是我想根据timeRegisted对数组进行排序。任何人都知道我可以根据时间对数组进行排序吗?
我非常感谢你的帮助。
答案 0 :(得分:0)
以下代码将对您的数组进行排序。它确实假设timeRegistered将转换为有效的日期。您应该添加对formatter.date返回的值的检查为非零
let array2 = array.sorted(by:{let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy HH:mm"
return formatter.date(from:$0.timeRegisted)! < formatter.date(from:$1.timeRegisted)!})
答案 1 :(得分:0)
我正在使用Alamofire和SwiftyJSON。
Alamofire.request(yourURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
.responseJSON { response in
switch(response.result) {
case .success(_):
var responseObject = JSON(response.result.value!).arrayValue
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
responseObject = responseObject.sorted(by: { [dateFormatter] (item1, item2) -> Bool in
return dateFormatter.date(from: item1["timeRegisted"].stringValue)!.compare(dateFormatter1.date(from: item2["timeRegisted"].stringValue)!) == ComparisonResult.orderedDescending
})
print(responseObject)
break
case .failure(_):
print(response.result.error ?? "Response is nil")
break
}
}