小编典典

如何从Swift中的字典中获取键的值?

swift

我有一本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"))
}

阅读 1468

收藏
2020-07-07

共1个答案

小编典典

使用下标访问字典键的值。这将返回一个可选:

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)")
}
2020-07-07