Ios 如何获取数组中的字典对象
我有一个Ios 如何获取数组中的字典对象,ios,swift,Ios,Swift,我有一个dict(NSDictionary),其中包含以下数据 { images = ( { image = "image.jpg"; scores = ( { "classifier_id" = "Adventure_Sport";
dict(NSDictionary)
,其中包含以下数据
{
images = (
{
image = "image.jpg";
scores = (
{
"classifier_id" = "Adventure_Sport";
name = "Adventure_Sport";
score = "0.662678";
},
{
"classifier_id" = Climbing;
name = Climbing;
score = "0.639987";
},
{
"classifier_id" = Flower;
name = Flower;
score = "0.628092";
},
{
"classifier_id" = "Nature_Scene";
name = "Nature_Scene";
score = "0.627548";
},
{
"classifier_id" = Icicles;
name = Icicles;
score = "0.617094";
},
{
"classifier_id" = Volcano;
name = Volcano;
score = "0.604928";
},
{
"classifier_id" = Potatoes;
name = Potatoes;
score = "0.602799";
},
{
"classifier_id" = "Engine_Room";
name = "Engine_Room";
score = "0.595812";
},
{
"classifier_id" = Bobsledding;
name = Bobsledding;
score = "0.592521";
},
{
"classifier_id" = White;
name = White;
score = "0.587923";
},
{
"classifier_id" = Yellow;
name = Yellow;
score = "0.574398";
},
{
"classifier_id" = "Natural_Activity";
name = "Natural_Activity";
score = "0.54574";
},
{
"classifier_id" = Butterfly;
name = Butterfly;
score = "0.526803";
},
{
"classifier_id" = "Dish_Washer";
name = "Dish_Washer";
score = "0.513662";
},
{
"classifier_id" = Rainbow;
name = Rainbow;
score = "0.511032";
}
);
}
);
}
我无法找到在数组中访问classifier\u id
的方法
我真的需要你的帮助。谢谢PS我已经试过了dict[“分数”]
和dict[“image.scores”]
请帮忙。。谢谢你想要的
let classifier_ids = dict["scores"].map{$0["classifier_id"]}
如果您的容器是NSObjects,而不是Swift字典和数组,那么您需要添加一些类型转换,但这是基本思想
此代码对于非类型集合更安全:
var classifier_ids: [String?]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.map{$0["classifier_id"]}
}
这将为您提供一个选项数组,如果数组中的某个条目不包含“分类器id”键/值对,则该条目将为零
或者,如果要跳过不包含“分类器id”键/值对的条目:
var classifier_ids: [String]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.flatmap{$0["classifier_id"]}
}
在某个时候采取一个步骤:
if let array = dict["images"] as? NSArray {
if let array2 = array[0]["scores"] as? NSArray {
if let ids = array2.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}
}
}
或一炮打响:
if let ids = (dict["images"]?[0]["scores"])?.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}
尝试dict[“图像”][0][“分数”][0][“分类器id”]作为第一个分类器id元素这太棒了。。。给我想要的。