Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")) } 
like image 650
DuyguK Avatar asked Sep 09 '14 09:09

DuyguK


People also ask

How do I get the value of a specific key in a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

How do you check if a value is in a dictionary Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.

Is dictionary value type in Swift?

In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data. You don't need to do anything special — such as making an explicit copy — to prevent other code from modifying that data behind your back.


2 Answers

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)") } 
like image 80
Prine Avatar answered Sep 27 '22 20:09

Prine


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." 
like image 45
Sebin Roy Avatar answered Sep 27 '22 21:09

Sebin Roy