我正在尝试对任何对象的数组进行排序,但无法对其进行排序。我从AnyObject格式的Parse数据库中获取了一些数据。根据以下数据,我想通过“NAME”对这个AnyObject数组进行排序。以下是我的代码 -
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;
}
非常感谢任何帮助。谢谢!
答案 0 :(得分:3)
它不是[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
})
答案 1 :(得分:1)
为什么将数组转换为[AnyObject]
而不是将数组转换为[[String:Any]]
表示Array
的{{1}}并告诉编译器该数组包含Dictionary
作为对象。
Dictionary
注意:截至您在每个数组字典中都有if let array = myArray as? [[String:Any]] {
let sortedArray = array.sorted(by: { $0["NAME"] as! String < $1["NAME"] as! String })
}
个值为NAME
的键时,我强行将其包含在下标中。
答案 2 :(得分:0)
如果需要,可以使用以下功能
//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
}