16. Dictionary in Swift

Dictionary is a very flexible alternative of array where you can keep your data in key : value pair. As we discussed in arrays that data is stored in a sequence and you can access them with index number.

var colors = ["RED","GREEN","BLUE","YELLOW"]

colors[0]
colors[1]

If you consider this array as dictionary, Your first value is RED and key to access this value is 0, your second value is GREEN and key is 1. Dictionary also works in same but with felxible ways. You can name your own index number (key).

var dictionary_name = [key : value, key : value, .....]

var colors = ["BL" : "BLUE", "RE" : "RED", "YE" : "YELLOW", "GR" : "GREEN"]

BL is key and BLUE is value of dictionary, value can be duplicate but keys are unique. Swift will throw an error if keys are duplicated.

Dictionary initialization

You can first declare a dictionary and initialize it later.

var postcode = [Int:String] ()

“postcode” dictionary contains key of integer type and value of string type and you can initialize like this:

postcode[1234] = "Kings Palace"

posecode[“BL”] is not acceptable because key must be integer type as it is mentioned in signature [Int : String] ().

Dictionary can be declared and initialized together. The following dictionary contains key and value, both are String type.

var colors = ["BL" : "BLUE", "RE" : "RED", "YE" : "YELLOW", "GR" : "GREEN"]

 

Dictionary Count

You can obtain the dictionary count by using function “count”.

var dCount = colors.count
println(dCount)

 

Access, update and remove values

You can access values BLUE and YELLOW by using keys BL and YE

println(colors["BL"])
println(colors["YE"])

You can add or update values in a same fashion. If key already exists, value will be updated otherwise new value will be inserted.

// Update if exists
colors["BL"] = "DARK BLUE"

// Add if does not exist
colors["WH"] = "WHITE"
colors.count

Another alternative of adding or inserting values is “updateValue” method

// Update if exists
colors.updateValue("RED BLOOD", forKey: "RE")

// Add if does not exist
colors.updateValue("PURPLE", forKey: "PR")

You can delete any value by assigning “nil”

colors["WH"] = nil

and alternative solution is

colors.removeValueForKey("WH")
colors.count

 

Access all elements of dictionary

Same like array, dictionary elements are accessible by using for loop.

for(key, value) in colors {

    println("My color code is \(key) and color name is \(value)")

}

You can assign any name to ‘key’ and ‘value’ in for loop

for(colorcode,colorname) in colors{

    println("My color code is \(colorcode) and color name is \(colorname)")

}

 

 

Download file from GitHub