簡體   English   中英

Swift 3:從返回nil訪問嵌套字典嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM