简体   繁体   English

Swift中可能存在多维词典?

[英]Multidimensional dictionaries possible in Swift?

Just learning Swift, coming from PHP. 刚学习Swift,来自PHP。 I'm trying to figure out if you can do deeply nested arrays in Swift. 我想弄清楚你是否可以在Swift中做深层嵌套数组。 Here's a PHP example of what I'm talking about: 这是我正在谈论的PHP示例:

$myArray = array(

"motorcycles" => array ("Honda", "Ducati", "Yamaha"),
"cars" => array(
                "sedans" => array("Jetta", "Taurus", "Impala"),
                "sport" => array("Porsche", "Ferarri", "Corvette"),
                "trucks" => array (
                                "shortbed" => array("Ford F150", "Dodge Ram 1500"),
                                "longbed" => array(
                                                    "standardCab" => array("Ford F350", "Dodge Ram 2500"),
                                                    "crewCab" => array("Ford F350", "Dodge Ram 2500")
                                                    )
                            )
            )

);

Yes, in Swift that would be: 是的,在Swift中会是:

let myArray = [
    "motorcycles": ["Honda", "Ducati", "Yamaha"],
    "cars": [
        "sedans": ["Jetta", "Taurus", "Impala"],
        "sport" : ["Porsche", "Ferarri", "Corvette"],
        "trucks" : [
            "shortbed" : ["Ford F150", "Dodge Ram 1500"],
            "longbed" : [
                "standardCab":["Ford F350", "Dodge Ram 2500"],
                "crewCab":["Ford F350", "Dodge Ram 2500"]
            ]
        ]
    ]
]

Reading values from such a structure can be a bit difficult though, since Swift has difficulty discerning the types. 从这样的结构中读取值可能有点困难,因为Swift难以辨别类型。 To get the standardCab vehicles, you can do: 要获得standardCab车辆,您可以:

if let trucks = myArray["cars"]?["trucks"] as? [String:AnyObject] {
    if let standardCab = trucks["longbed"]?["standardCab"] as? [String] {
        println(standardCab)
    }
}

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

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