Swift中可能存在多维词典?

时间:2014-11-02 01:25:41

标签: swift

刚学习Swift,来自PHP。我试图弄清楚你是否可以在Swift中做深层嵌套数组。这是我所谈论的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")
                                                    )
                            )
            )

);

1 个答案:

答案 0 :(得分:8)

是的,在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"]
            ]
        ]
    ]
]

从这样的结构中读取值可能有点困难,因为Swift难以辨别类型。要获得standardCab车辆,您可以执行以下操作:

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