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

DuyguK picture DuyguK · Sep 9, 2014 · Viewed 172.2k times · Source

I have a Swift dictionary. I want to get my key's value. Object for key method is not working for me. How do you get the value for a dictionary's key?

This is my dictionary:

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

for name in companies.keys { 
    print(companies.objectForKey("AAPL"))
}

Answer

Prine picture Prine · Sep 9, 2014

Use subscripting to access the value for a dictionary key. This will return an Optional:

let apple: String? = companies["AAPL"]

or

if let apple = companies["AAPL"] {
    // ...
}

You can also enumerate over all of the keys and values:

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

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

Or enumerate over all of the values:

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