Dictionary is another collection type available in Swift. Dictionary can store multiple values of same type. Dictionary is a key value pair collection, where each key has a value associated with it. Dictionary in Swift are different from NSDictionary in objective C. The common difference between the two is that NSDictionary can store different values whereas swift’s dictionary can store value of single type. This means if you created dictionary that is going to store int value then it can only store int value and no other types value are permitted to be stored in swift’s dictionary. Like array, dictionary does not contain ordered set of items. The only restriction, dictionary has that its key should be unique.
Create and initialize Dictionary:
To create a swift dictionary you can use below syntax
var mySwiftDictionary =
The above line of code creates am empty mySwiftDictionary with its key’s of String type and value’s are also of String type.
To make a dictionary empty if its already initialized the you can use simple [:] (colon inside square brackets) to your dictionary
mySwiftDictionary = [:]
The above line of code will set mySwiftDictionary to an empty dictionary.
You can also create a dictionary using literals
vat mySwiftDictionary = [“Key1″:”Value1″,”Key2″:”Value2”]
Here Swift automatically infer that Dictionayr
Accessing, modifying dictionary:
You can access and modify Swift’s dictionary by using properties and methods. To get the count of number of items in Swift dictionary, you can use count property.
println(“mySwiftDictionary contains (mySwiftDictionary.count) items.” )
You can add new item to dictionary by using below code
mySwiftDictionary[“Key3″]=”Value3”
Above code will add new item to dictionary.
To update a value for a particular key, you can use
mySwiftDictionary[“Key3″]=”Value3 Updated”
To get a value for a particular key associated with dictionary, you can use
var myValue = mySwiftDictionary[“Key1”]
println(“vlue is (myValue)”)
It will print Value1 as value for the Key1 is Value1.
To remove a key value pair from dictionary you have to simply set nil value to the key
mySwiftDictionary[“Key1”] = nil
Key1 is now removed from the mySwiftDictionary.
Swift also provides two methods for set or update a value for a key and remove key value pair from dictionary. These are
updateValue(forKey:) :- This will update a value for the key if exists, otherwise set a new key value pair in the dictionary.
mySwiftDictionary.updateValue(“Value4″, forKey:”Key4”)
The above code line will set a new key value pair as we did not have Key4 in our mySwiftDictionary.
removeValueForKey():- This method will remove a key value pair from the dictionary for the key specified in the square brackets.
mySwiftDictionary.removeValueForKey(“Key4”)
The above line of code will remove Key4 from the mySwiftDictionary.