2017-02-14 50 views
0

我想排序anyobject的數組,但無法做到這一點。我從Parse數據庫以AnyObject格式獲取一些數據。根據以下數據,我想按「NAME」對這個AnyObject數組進行排序。下面是我的代碼 -anyobject排序數組Swift 3

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的是這樣的 -

{ 
      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; 
     } 

任何幫助將非常感激。謝謝!

回答

1

爲什麼轉換陣列[AnyObject]的而不是轉換陣列到[[String:Any]]意味着DictionaryArray並告訴數組包含Dictionary爲對象的編譯器。

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

注:當你在你的陣列中的每個字典與StringNAME鍵我有力量與標包起來。

2

這不是[AnyObject](我沒有想法的數組),它是字典數組[[String:Any]]。更具體地說,這解決了錯誤。

在Swift 3中,編譯器必須知道所有下標對象的具體類型。

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