【发布时间】:2018-02-14 08:33:18
【问题描述】:
我试图弄清楚如何通过值“名称”过滤掉 NSArrays 的字典
// Is an Array of a dictionary, by key : values
var teamFilteredList = [[String:Any]]()
var teamList = [[String:Any]]()
获取:
let string = "https://api/connect/"
let url = NSURL(string: string)
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
let session = URLSession.shared
let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray {
print(jsonObj)
teamList = jsonObj as! [[String : Any]]
DispatchQueue.main.async {
self.teamCollectionView.reloadData()
}
}
}
tache.resume()
此代码是结果并被放入 teamList
JSON:
({
id = 1;
logo = "testLogo";
name = "testTeam1";
"url" = "https://example.com";
},
{
id = 2;
logo = "testLogo";
name = "testTeam2";
"url" = "https://example.com";
},
{
id = 3;
logo = "testLogo";
name = "testTeam3";
"url" = "https://example.com";
})
放入 teamList 后的外观示例:
let example = [[id: "1", logo: "image", name: "testTeam1", url: "https"], [id: "2", logo: "image", name: "testTeam2", url: "https"]]
试图过滤的代码:
let array2Name = teamFilteredList.flatMap { $0["name"] }
teamFilteredList = teamList.reduce(teamFilteredList, { result, value in
!array2Name.contains(where: { $0 as! _OptionalNilComparisonType == value["testTeam3"] }) ? result + [value]: result
})
到目前为止,这段代码很糟糕。但是网上没有其他东西可以告诉我如何做到这一点。所以我被卡住了。
导致崩溃:
无法转换“__NSCFString”类型的值
更新:
我有一个集合视图,它是由 NSURL 从获取中填充的,它给了我一个充满 NSArrays 的字典,我想通过一个已经在 NSArray 索引中的值过滤掉该字典中的所有 NSArray 索引键:“名称”
此链接最终答案中已回答的问题,但它不是最新的并且会产生错误。 here
【问题讨论】:
-
无法转换类型为 '__NSCFString 的值。您正在尝试将 String 存储到另一种数据类型。所以它越来越崩溃
-
好的,谢谢,必须有一个更简单的方法来做到这一点。 @McDonal_11
-
你想做什么?
-
我把它放在更新中@McDonal_11
-
鼓励您使用自定义类或结构而不是字典。它让事情变得简单。