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


83

我有一本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"] { … }
Martin R

Answers:


167

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

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

24

从Apple Docs

您可以使用下标语法从字典中检索特定键的值。因为可以请求不存在任何值的键,所以字典的下标返回字典值类型的可选值。如果字典中包含所请求键的值,则下标将返回一个可选值,其中包含该键的现有值。否则,下标返回nil:

https://developer.apple.com/documentation/swift/dictionary

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."
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.