How can I get key's value from dictionary in Swift?

拈花ヽ惹草 提交于 2019-11-27 11:01:55

问题


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

  }

回答1:


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 {
    print("\(key) -> \(value)")
}

Or if you only want the values:

for value in Array(companies.values) {
    print("\(value)")
}

One value with direct access on the dictionary:

print(companies["AAPL"])



回答2:


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:

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."


来源:https://stackoverflow.com/questions/25741114/how-can-i-get-keys-value-from-dictionary-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!