iOS Development with Swift 2 - Dictionaries



A dictionary is a collection that stores values in a key value pair, i.e. the data stored in a dictionary is stored in a method where each value is related to a key. Here, every key is unique and cannot appear twice in the same dictionary. Whereas the value related to keys may be repeating/Duplicate. A dictionary is not stored in any order and it can be accessed using the keys.

Creating an Empty Dictionary

The following command will create an empty dictionary where the key will be the integer and the value will be of String Data type.

var DictionaryName = [Int : String]()

A dictionary is stored like −

[key1: value1 , key2 : value2 , key3 : value3 ……]

Assigning Values to Dictionary

Let us consider the following example that shows how values are assigned to the dictionary.

var airports = [String : String]() 
airports = [“Delhi” : “IGI” , “Bengaluru”:”Kempegowda”,”DelhiTwo”: “Safdarjung”] 

Operations on Dictionary

The following points describe the various operations that are performed on a dictionary.

  • DictionaryName.count − returns the number of key-value pairs in dictionary.

  • DictionaryName.isEmpty − returns true if dictionary is empty.

  • DictionaryName[Key] = Value − Adds the key value pair to Dictionary.

  • DictionaryName.updateValue(“Value” ,forKey : “key”) − Updates a key, if exist.

  • DictionaryName.removeValue(forKey : key) − removes the value for key.

Operations On Dictionary
ios_development_with_swift2_playground.htm
Advertisements