我有一个包含以下数据的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";
}
);
}
);
}我想不出在数组中访问classfier_id的方法
真的需要你的帮助。谢谢。另外,我已经尝试过dict["scores"]和dict["image.scores"]了
请帮帮忙..谢谢
发布于 2016-03-10 05:00:56
你想要的
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"]}
}这将为您提供一个可选数组,其中如果数组中条目不包含"classifier_id“键/值对,则给定条目将为空。
或者,如果您想跳过不包含"classifier_id“键/值对的条目:
var classifier_ids: [String]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.flatmap{$0["classifier_id"]}
}发布于 2016-03-10 05:23:01
一次走一步:
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)
}https://stackoverflow.com/questions/35901933
复制相似问题