快速排序字典数组并获取运算符不能应用于任何

时间:2018-07-17 06:30:53

标签: arrays swift sorting

我正在尝试按array的值Dictionaries从最新到最早对timeStamp进行排序

错误:二进制运算符'<'无法应用于两个'Any?'操作数

timeStamp的值作为Int保存到Dictionary中:

timeStamp = inviteDict["timeStamp"] as? Int

字典:

[
"type": "invite",
"complimentId": key,
"status": status,
"timeStamp": timeStamp!,
 "fromUser": user
]

功能-合并两个arrays元组,在通过array传递之前,我需要按timeStamphandler进行排序:

    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

3 个答案:

答案 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
})

如瓦迪安建议在这种情况下使用自定义结构。