sort array of anyobject Swift 3

允我心安 提交于 2019-12-02 08:01:58

Why are converting array to [AnyObject] instead of that convert the array to the [[String:Any]] means Array of Dictionary and tell the compiler that array contains Dictionary as objects.

if let array = myArray as? [[String:Any]] {
   let sortedArray = array.sorted(by: { $0["NAME"] as! String < $1["NAME"] as! String })
}

Note: As of you are having NAME key with String value in your each dictionaries of array I have force wrapped it with the subscript.

It's not [AnyObject] (array of I-have-no-idea), it's array of dictionaries [[String:Any]]. Be more specific, this resolves the error.

In Swift 3 the compiler must know the specific type of all subscripted objects.

let sortedArray = (myArray as! [[String:Any]]).sorted(by: { (dictOne, dictTwo) -> Bool in
                                         let d1 = dictOne["NAME"]! as String
                                         let d2 = dictTwo["NAME"]! as String

                                         return d1 < d2
                                     })

You can use below function if you want

//function to sort requests
func sortRequests(dataToSort: [[String:Any]]) -> [[String:Any]] {
    print("i am sorting the requests...")
    var returnData = [[String:Any]]()
    returnData = dataToSort
    returnData.sort{
            let created_date0 = $0["date"] as? Double ?? 0.0
            let created_date1 = $1["date"] as? Double ?? 0.0
            return created_date0 > created_date1
    }
    return returnData
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!