我有一本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"))
}
我有一本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"))
}
if let airportName = airports["DUB"] { … }
”
Answers:
使用下标访问字典键的值。这将返回一个可选:
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)")
}
从Apple Docs
您可以使用下标语法从字典中检索特定键的值。因为可以请求不存在任何值的键,所以字典的下标返回字典值类型的可选值。如果字典中包含所请求键的值,则下标将返回一个可选值,其中包含该键的现有值。否则,下标返回nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."