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

Duy*_*guK 74 dictionary key-value 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"))

  }
Run Code Online (Sandbox Code Playgroud)

Pri*_*ine 142

使用此方法,您可以看到键和值.

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

for (key, value) in companies {
    print("\(key) -> \(value)")
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想要值:

for value in Array(companies.values) {
    print("\(value)")
}
Run Code Online (Sandbox Code Playgroud)

在字典上直接访问的一个值:

print(companies["AAPL"])
Run Code Online (Sandbox Code Playgroud)


Seb*_*Roy 22

来自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."
Run Code Online (Sandbox Code Playgroud)


Rez*_*rim 6

为了找到价值,请使用下面的

if let a = companies["AAPL"] {
   // a is the value
}
Run Code Online (Sandbox Code Playgroud)

用于遍历字典

for (key, value) in companies {
    print(key,"---", value)
}
Run Code Online (Sandbox Code Playgroud)

最后,为了按值搜索键,您首先添加扩展名

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需调用

companies.findKey(val : "Apple Inc")
Run Code Online (Sandbox Code Playgroud)