获取Swift中复杂嵌套字典/数组组合的Key值

时间:2016-03-08 15:14:13

标签: ios swift

我正在尝试访问以下词典的键:

let dictionaryToUSe = ["Starter":["mealName":"hamburger","price":"20.00"],"MainCourse":["mealName":"hotdog","price":"30.00"] ]
let keysToUse = dictionaryToUSe.keys  
print(keysToUse) // returns "LazyMapCollection<Dictionary<String, Dictionary<String, String>>, String>(_base: ["Starter": ["price": "20.00", "mealName": "hamburger"]], _transform: (Function))\n"

如何访问&#34; starter&#34;串? 以及如何为&#34; dictionaryToUSe&#34;生成密钥列表?字典?

1 个答案:

答案 0 :(得分:2)

要获取字典键列表,请从LazyMapCollection:

生成一个数组
let keysToUse = Array(dictionaryToUSe.keys)

结果:

  

[“Starter”,“MainCourse”]

但是要访问字典中的值,请使用经典的下标:

if let starter = dictionaryToUSe["Starter"] {
    print(starter)  // ["price": "20.00", "mealName": "hamburger"]
    if let price = starter["price"] {
        print(price) // "20.00"
    }
    // etc
}