110

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"))
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
DuyguK
  • 4,250
  • 9
  • 33
  • 46
  • 5
    That's all covered in the documentation: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_180 – Martin R Sep 09 '14 at 09:39
  • *"You can also use subscript syntax to retrieve a value from the dictionary for a particular key … `if let airportName = airports["DUB"] { … }` "* – Martin R Sep 09 '14 at 11:27

4 Answers4

213

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)")
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Prine
  • 12,192
  • 8
  • 40
  • 59
26

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:

https://developer.apple.com/documentation/swift/dictionary

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."
Community
  • 1
  • 1
Sebin Roy
  • 834
  • 9
  • 10
6

For finding value use below

if let a = companies["AAPL"] {
   // a is the value
}

For traversing through the dictionary

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

Finally for searching key by value you firstly add the extension

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

Then just call

companies.findKey(val : "Apple Inc")
Rezaul Karim
  • 830
  • 8
  • 15
-1
var dic=["Saad":5000,"Manoj":2000,"Aditya":5000,"chintan":1000]

print("salary of Saad id \(dic["Saad"]!)")

for accessing members of dictionary you must have to include !(Exclamation)
!=>it means force unwrapping Documentation for force Unwrappingdetails