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

时间:2021-02-10 20:57:26

I am early bird in swift. I have a dictionary.I want to get my key's value.Object for key method is not worked for me.Can anybody help me please?

我是敏捷的早起鸟。我有一个字典。我想知道我的钥匙的价值。键方法对象对我不起作用。谁能帮帮我吗?

This is my dictionary;

这是我的字典;

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

    for (name) in companies.key {

println(companies.objectForKey("AAPL"))

  }

2 个解决方案

#1


110  

With this method you see the key and the value.

通过这个方法,您可以看到键和值。

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    println("\(key) -> \(value)")
}

Or if you only want the values:

或者如果你只想要这些值:

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

One value with direct access on the dictionary:

直接访问字典的一个值:

println(companies["AAPL"])

#2


17  

From Apple Docs

从苹果公司文档

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

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

#1


110  

With this method you see the key and the value.

通过这个方法,您可以看到键和值。

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    println("\(key) -> \(value)")
}

Or if you only want the values:

或者如果你只想要这些值:

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

One value with direct access on the dictionary:

直接访问字典的一个值:

println(companies["AAPL"])

#2


17  

From Apple Docs

从苹果公司文档

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

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