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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With