[英]Swift 3: Accessing nested dictionary from returns nil?
我在嘗試訪問嵌套的Dictionary
遇到問題,該Dictionary
似乎返回nil
。
這是我的info
輸出的類型Dictionary<String, Any>
:
info = ["list_order": 1, "name": Some Text, "id": 1, "menu_items": {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}]
info["menu_items"]
的輸出:
info["menu_items"] = {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
id = 1;
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}
但是,以下分配在test
產生nil
:
let test = info["menu_items"] as? Dictionary<Int, Any>
有什么不明顯的東西還是我不了解基本原理?
如果您的鍵不是Int
類型,則很可能是String
類型,請使用[String: Any]
嘗試一次。
if let menuItems = info["menu_items"] as? [String: Any] {
print(menuItems)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.