如何从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"))

}

回答:

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

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)")

}

以上是 如何从Swift中的字典中获取键的值? 的全部内容, 来源链接: utcz.com/qa/434150.html

回到顶部