我有一本Swift字典。我想获得钥匙的价值。密钥方法的对象对我不起作用。如何获得字典键的值?
这是我的字典:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] for name in companies.keys { print(companies.objectForKey("AAPL")) }
使用下标访问字典键的值。这将返回一个可选:
let apple: String? = companies["AAPL"]
要么
if let apple = companies["AAPL"] { // ... }
您还可以枚举所有键和值:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] for (key, value) in companies { print("\(key) -> \(value)") }
或枚举所有值:
for value in Array(companies.values) { print("\(value)") }