我正在尝试按array
的值Dictionaries
从最新到最早对timeStamp
进行排序
错误:二进制运算符'<'无法应用于两个'Any?'操作数
timeStamp
的值作为Int
保存到Dictionary
中:
timeStamp = inviteDict["timeStamp"] as? Int
字典:
[
"type": "invite",
"complimentId": key,
"status": status,
"timeStamp": timeStamp!,
"fromUser": user
]
功能-合并两个arrays
元组,在通过array
传递之前,我需要按timeStamp
对handler
进行排序:
func getInvitesAndCompliments(forUserId forId: String, handler: @escaping ([[String : Any]], Bool) -> ()){
var invitesAndCompliments = [[String : Any]]()
var invites = [[String : Any]]()
var compliments = [[String : Any]]()
getComplimentsReceived(forUserId: forId) { (complimentsDict, success) in
invitesAndCompliments.removeAll()
compliments = complimentsDict
invitesAndCompliments = invites + compliments
handler(invitesAndCompliments, true)
}
getInvitesReceived(forUserId: forId) { (invitesDict, success) in
invitesAndCompliments.removeAll()
invites = invitesDict
invitesAndCompliments = compliments + invites
//sort array by timeStamp value
let sorted_invitesAndCompliments = invitesAndCompliments.sorted(by: { $0["timeStamp"] < $1["timeStamp"] })
handler(sorted_invitesAndCompliments, true)
}
}//end func
答案 0 :(得分:3)
如下更新代码:
let sorted_invitesAndCompliments = invitesAndCompliments.sorted { ($0["timeStamp"] as! Int) < ($1["timeStamp"] as! Int)}
我希望这对您有用。
答案 1 :(得分:1)
从字典中获取值的结果始终是Any?
,您必须精简类型
let sorted_invitesAndCompliments = invitesAndCompliments.sorted(by: { ($0["timeStamp"] as! Int) < $1["timeStamp"] as! Int })
为避免这种情况,请使用自定义结构。
答案 2 :(得分:1)
我建议不要使用强制转换,如果值为空,则可能会崩溃。检查以下代码:
let sorted_invitesAndCompliments = invitesAndCompliments.sorted(by: {
guard let timestamp1 = $0["timeStamp"] as? Int else {return false}
guard let timestamp2 = $1["timeStamp"] as? Int else {return false}
return timestamp1 < timestamp2
})
如瓦迪安建议在这种情况下使用自定义结构。