Search code examples
iosarrayssortingdictionaryanyobject

sort array of anyobject Swift 3


I am trying to sort an array of anyobject, but not able to do it.I get some data from Parse database in AnyObject format. As per below data, I want to sort this AnyObject array by "NAME". Below is my code -

  let sortedArray = (myArray as! [AnyObject]).sorted(by: { (dictOne, dictTwo) -> Bool in
                                                            let d1 = dictOne["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"
                                                            let d2 = dictTwo["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"

                                                            return d1 < d2
                                                        })

myArray looks like this -

 {
            LINK = "www.xxx.com";
            MENU = Role;
            "MENU_ID" = 1;
            NAME = "A Name";
            SUBMENU = "XXX";
            "Training_ID" = 2;
        },
            {
            LINK = "www.xyz.com";
            MENU = Role;
            "MENU_ID" = 2;
            NAME = "B name";
            SUBMENU = "jhjh";
            "Training_ID" = 6;
        },
            {
            LINK = "www.hhh.com";
            MENU = Role;
            "MENU_ID" = 3;
            NAME = "T name";
            SUBMENU = "kasha";
            "Training_ID" = 7;
        },
            {
            LINK = "www.kadjk.com";
            MENU = Role;
            "MENU_ID" = 5;
            NAME = "V name";
            SUBMENU = "ksdj";
            "Training_ID" = 1;
        },
            {
            LINK = "www.ggg.com";
            MENU = Role;
            "MENU_ID" = 4;
            NAME = "K name";
            SUBMENU = "idiot";
            "Training_ID" = 8;
        },
            {
            LINK = "www.kkk.com";
            MENU = Role;
            "MENU_ID" = 6;
            NAME = "s name";
            SUBMENU = "BOM/ABOM/BSM";
            "Training_ID" = 12;
        }

Any help would be much appreciated. Thanks!


Solution

  • 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.