我如何从Swift中的字典中获得密钥的值?

我很快就早鸟 我有一本字典。我想得到我的钥匙的价值。钥匙方法的对象不适合我。可以有人帮我吗?

这是我的字典;

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] for (name) in companies.key { println(companies.objectForKey("AAPL")) } 

用这种方法你可以看到键和值。

 var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] for (key, value) in companies { println("\(key) -> \(value)") } 

或者,如果你只想要的价值:

 for value in companies.values.array { println("\(value)") } 

直接访问字典的一个值:

 println(companies["AAPL"]) 

从苹果文件

您可以使用下标语法从字典中检索特定键的值。 因为可以请求没有值的键,所以字典的下标返回字典值types的可选值。 如果字典包含请求键的值,则下标返回包含该键的现有值的可选值。 否则,下标返回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."