Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)


Dictionaries in Swift are like arrays in special characteristics, such as mutable and strongly typed. Dictionary is mutable by default, except if used with let. Also keys and values should be of the same type.

The dictionary type is inferred by the initial values, or you can explicitly write it using the square brackets [keyType, valueType].

Initializing a dictionary

To initialize a dictionary, you have two options. The first option is to create an empty one with no data. You can create it like this:

var dic1 = [String:Int]() // 0 key/value pairs

As we see in this case, we had to explicitly write the type of keys and values.

In the second option, you have the predefined values like this:

var dic2 = ["EN" : "English", "FR" : "French"]
//["EN": "English", "FR": "French"]

Here we didn't write the type of keys or the values, as it was inferred from the initial values.

Appending or updating values

Updating or appending a value with a key in a dictionary is very similar, and can be done like this:

dic2["AR"] = "Arabic" //Add
dic2["EN"] = "ENGLISH" //update
//["EN": "ENGLISH", "FR": "French", "AR": "Arabic"]

As you can see, in the first line it will create a new record in the dictionary, because the "AR" key did not exist before. In the second line as the "EN" key exists, it will update each of its values with the given one. Very simple right!

Another method to update a value for the key in the dictionary is to call updateValue(val, forKey:). Take a look at the following example:

dic2.updateValue("ARABIC", forKey: "AR") //returns "Arabic"
//dic2 now is ["EN": "ENGLISH", "FR": "French", "AR": "ARABIC"]

As you see in the code, this method returns the old value after updating the new value. So, if you want to retrieve the old value after the update function is done, this method is the best choice.

Removing items from the dictionary

This is the same as updating values. You have two ways to remove items from dictionary. The first is to set the value of the key as nil, and the second is to call the removeValueForKey(key) method. This method also returns the old value before deleting it.

dic2["AR"] = nil
dic2.removeValueForKey("FR") //returns French
//["EN": "ENGLISH"]
dic2["FR"]  // Returns nil