简体   繁体   English

Swift 2.0:如何声明嵌套词典?

[英]Swift 2.0: How To Declare Nested Dictionaries?

I'm trying to do a complex Swift Dictionary declaration similar to a JSON packet. 我正在尝试做一个类似于JSON数据包的复杂Swift字典声明。 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. 我想知道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. 您应该创建一些模型类型(最好是structs )并将其组合。

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. 在这种情况下,您实际上是在声明一个字典数组,而不是一个字典字典: [Any:[Any:Any]] (或者,根据您的数据,更好的是) [String:[String:Any]]但这赢了无法使用,因为categories键值实际上是一个数组,而不是字符串。 At that point you're left with just [String:Any] 那时您只剩下[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. 但是,最重要的是,采用@appzYourLife的方法并定义适当的模型类型会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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