试图在Swift中访问嵌套的字典数组中的键

时间:2016-12-28 13:12:27

标签: ios arrays swift dictionary

也许我没有正确地说出问题,但是我需要访问嵌套在另一个字典数组中的字典数组中的键。我认为最接近的是

name: dict["name"] as! String,
speciesId: dict["species_id"] as! Int,
identifier: dict["identifier"] as! String,
typeId: dict["forms"]!["item0"]!["type_id"] as! Int

我可以抓住前3个变量,但不能抓住最后一个变量,因为它嵌套在另一个字典数组中。如果有人能指出我正确的方向抓住 type_id 。当我尝试

typeId: dict["type_id"] as! Int

它在控制台上只返回nil。

更新:所以在这里找到一个答案,使用这一行来从一个数组中获取一个int

 formId: (dict["egg_groups"] as! Array<Int>)[0] as Int!

但是当我尝试从数组中获取一个dict时,我得到了EXC_BAD INSTRUCTION

1 个答案:

答案 0 :(得分:2)

试试这个并传递正确的索引,因为这里是0:

let typeId = (dict["forms"] as! Array<Dictionary<String,Any>>)[0]["type_id"]! as Int
相关问题