Swift中Dictionary中的名称键/值对

时间:2014-11-09 00:31:44

标签: cocoa swift

是否可以通过&amp ;;访问keyvalueDictionary条目。 ,而非 0 &的 1

在示例中:

let rockyPlanets: Dictionary<String, Int> = [
    // Alphabetical order
    "Earth": 3, "Mars": 4, "Mercury": 1, "Venus": 2
]
for eachPlanet in rockyPlanets {
    println("\(eachPlanet.0) is at position \(eachPlanet.1)")
}

如何以这种方式通过(而不是索引)访问键/值:

for eachPlanet in rockyPlanets {
    println("\(eachPlanet.key) is at position \(eachPlanet.value)")
}

1 个答案:

答案 0 :(得分:4)

这是你在找什么?

for (key, value) in someDict {
    // ...
}

在你的情况下:

for (planet, position) in rockyPlanets {
    println("\(planet) is at position \(position)")
}