Showing posts with label Dictionaries. Show all posts
Showing posts with label Dictionaries. Show all posts

Friday, June 12, 2015

Dictionaries


Swift only provides two collection types. One is arrays and the other is dictionaries. Each value in a dictionary is associated with a unique key. If you’re familiar with NSDictionary in Objective C, the syntax of initializing a dictionary in Swift is similar. Here is an example:

Objective C:

NSDictionary *companies = @{@"AAPL" : @"Apple Inc", @"GOOG" : @"Google Inc", @"AMZN" :@"Amazon.com, Inc", @"FB" : @"Facebook Inc"};

Swift:

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

The key and value in the key-value pairs are separated by a colon. Like array and other variables, Swift automatically detects the type of the key and value. However, if you like, you can specify the type information by using the following syntax:

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

To iterate through a dictionary, use the for-in loop.

for (stockCode, name) in companies {
    println("\(stockCode) = \(name)")
}


You can also use the keys and values properties to retrieve the keys and values of the dictionary.

for stockCode in companies.keys {
    println("Stock code = \(stockCode)")
}
for name in companies.values {
    println("Company name = \(name)")
}


To access the value of a particular key, specify the key using the subscript syntax. If you want to add a new key-value pair to the dictionary, simply use the key as the subscript and assign it with a value like below:

companies["TWTR"] = "Twitter Inc"

Now the “companies” dictionary contains a total of 5 items. The “TWTR”:”Twitter Inc” pair is automatically added to the “companies” dictionary.