Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0: How To Declare Nested Dictionaries?

I'm trying to do a complex Swift Dictionary declaration similar to a JSON packet. However, the compiler is fighting me tooth and nail. Here's what I'm trying to do:

var icons: [[Any:Any]] = [
    "categories:":[
        ["cat2" : [
            ["name":"ImageName","type":"image"],
            ["name":"ImageName","type":"scroll","panel":panel1],
            ["name":"ImageName","type":"chooser","panel":[
                ["name":"ImageName"]]]
            ]
        ],
        ["cat2" : ["name":"ImageName"]],
        ["cat3" : ["name":"ImageName"]],
        ["cat4" : ["name":"ImageName"]],
        ["cat5" : ["name":"ImageName"]]
    ],
    "size":["x":"128","y":"128"]
]

I'm not sure how to declare this. As you can tell, I have the first element as a String, and the following sub elements as additional Dictionaries.

I want to know a best of practice method for these data structures in Swift.

Thank you in advance.

like image 687
Mark Löwe Avatar asked Feb 19 '16 22:02

Mark Löwe


2 Answers

The right way is NOT to use a dictionary.

You should create a few model types (preferably structs) and combine them.

Otherwise managing a dictionary like this will be hell.

like image 178
Luca Angeletti Avatar answered Sep 20 '22 09:09

Luca Angeletti


In this case, you're actually declaring an array of dictionaries, not a dictionary of dictionaries: [Any:[Any:Any]] (or better yet, given your data) [String:[String:Any]] But that won't work because the categories key value is actually an array, not a string. At that point you're left with just [String:Any]

The bottom line, however, is that you're going to be much better off taking @appzYourLife's approach and defining appropriate model types.

like image 34
David Berry Avatar answered Sep 19 '22 09:09

David Berry