简体   繁体   中英

Swift 3: Accessing nested dictionary from returns nil?

I'm having a problem trying to access a nested Dictionary , which seems to return nil .

Here's the output my info of type 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;
    };
}]

The output of 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;
    };
}

However, the following assigning produces a nil in test :

let test = info["menu_items"] as? Dictionary<Int, Any>

Is there something not obvious or am I not understanding basic fundamentals?

If your key is not Int type then most probably it is of String type, try once using [String: Any] .

if let menuItems = info["menu_items"] as? [String: Any] {
     print(menuItems)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM