Swift Dictionary

In this tutorial, you will learn about what dictionary is, creating a dictionary and some common operations in dictionary.

In the previous Swift Arrays article, we learned how we can store multiple values in a variable/constant. In this article, we are going to discuss how we can store data/values as key value pairs.

What is a dictionary?

A dictionary is simply a container that can hold multiple data as key-value pair in an unordered way.

Each value is associated with a unique key and stores data in unordered list as of Sets, i.e. you don't get the elements in the same order as you defined the items in the dictionary.

You may use dictionary instead of array when you need to look up value with some identifier in the collection. Suppose, you may want to search the capital city of country. In that case, you will create a dictionary with key country and value capital city. Now, you get the capital city from the collection by searching with the key country.

In simple terms, you pair a key to a value. In the above example, we paired a country to its capital city.


How to declare a dictionary in Swift?

You can create an empty dictionary by specifying the key:value Data type inside square brackets [].

Example 1: Declaring an empty dictionary

let emptyDic:[Int:String] = [:]
print(emptyDic)

When you run the program, the output will be:

[:]

OR

You can also define an empty dictionary as below:

let emptyDic:Dictionary<Int, String> = [:]
print(emptyDic)

In the above program, we have declared a constant emptyDic of type dictionary with key of type Int and value of type String and initialized it with 0 values.

OR

Since, Swift is a type inference language, you can also create dictionary directly without specifying the Data Type but must initialize with some values so that compiler can infer its type as:


Example 2: Declaring an dictionary with some values

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
print(someDic)

When you run the program, the output will be:

["b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, "h": 8]

In the above program, we have declared a dictionary without defining the type explicitly but initializing with some default elements.

The element is in key:value pair where key is of type String and value is of Int type. Since dictionary is an unordered list print(someDic)outputs the values in different order than defined.


Example 3: Creating dictionary from two arrays

We can also create a dictionary using arrays.

let customKeys = ["Facebook", "Google", "Amazon"]
let customValues = ["Mark", "Larry", "Jeff"]
let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues))
print(newDictionary)

When you run the program, the output will be:

["Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark"]

In the above program,zip(customKeys,customValues) creates a new Sequence of tuple with each element representing value from customKeys and customValues. To learn more about how zip works, visit Swit zip.

Now, we can pass this sequence to the Dictionary(uniqueKeysWithValues:) initializer and create a new Dictionary. Therefore, print(newDictionary) outputs a new Dictionary with elements from two arrays.


How to access dictionary elements in Swift?

As arrays, you can access elements of a dictionary by using subscript syntax. You need to include key of the value you want to access within square brackets immediately after the name of the dictionary.

Example 4: Accessing elements of a dictionary

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
print(someDic["a"])
print(someDic["h"])

When you run the program, the output will be:

Optional(1)
Optional(8)

You can also access elements of an dictionary using for-in loops.


Example 5: Accessing elements of an dictionary with for-in loop

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
for (key,value) in someDic {
    print("key:\(key) value:\(value)")
}

When you run the program, the output will be:

key:b value:2
key:a value:1
key:i value:9
key:c value:3
key:e value:5
key:f value:6
key:g value:7

How to modify dictionary elements in Swift?

You can add elements of in dictionary by using subscript syntax. You need to include new key as the subscript index and assign a new value of the type as of Dictionary.

Example 6: Setting elements in a dictionary

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
someDictionary["Japan"] = "Tokyo"
print(someDictionary)

When you run the program, the output will be:

["Japan": "Tokyo", "China": "Beijing", "India": "NewDelhi", "Nepal": "Kathmandu"]

In the above example, we've created a new key-value pair "Japan": "Tokyo" in the given dictionary by using the subscript syntax.

You can also use subscript syntax to change the value associated with a particular key as:


Example 7: Changing elements of a dictionary

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
someDictionary["Nepal"] = "KATHMANDU"
print(someDictionary)

When you run the program, the output will be:

["China": "Beijing", "India": "NewDelhi", "Nepal": "KATHMANDU"]

Some helpful built-in Dictionary functions & properties

1. isEmpty

This property determines if an dictionary is empty or not. It returns true if a dictionary does not contain any value otherwise returns false.

Example 8: How isEmpty works?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.isEmpty)

When you run the program, the output will be:

false

2. first

This property is used to access the first element of a dictionary.

Example 9: How first works?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.first)

When you run the program, the output will be:

Optional((key: "China", value: "Beijing"))

3. count

This property returns the total number of elements (key-value pair) in a dictionary.

Example 10: How count works?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.count)

When you run the program, the output will be:

3

4. keys

This property returns all the keys inside the dictionary.

Example 11: How keys works?

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let dictKeys  = Array(someDictionary.keys)
print(dictKeys)

When you run the program, the output will be:

["China", "India", "Nepal"]

Similarly, you can use values to get all the values inside the dictionary.


5. removeValue

This function removes and returns the value specified with the key from the dictionary. Both key value pair will be removed from the dictionary.

Example 12: How removeValue() works?

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val  = someDictionary.removeValue(forKey: "Nepal")
print(val)
print(someDictionary)

When you run the program, the output will be:

Optional("Kathmandu")
["India": "NewDelhi", "China": "Beijing"]

Similarly, you can also use removeAll function to empty an dictionary.


Things to Remember

1. While using subscript syntax to access elements of an dictionary in Swift, you must be sure the key lies in the index otherwise you will get a nil value. Let's see this in example:

Example 13: Key must be present

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val  = someDictionary["Japan"]
print(val)

When you run the program, the output will be:

nil

In the above program, there is no key Japan. So when you try to access the value of the key "Japan", you will get a nil value.

2. Likewise, key-values are case-sensitive in Swift, so you must make sure the correct cased key/value is used. Otherwise, you will get a nil value. Let's see this in example:

Example 14: Keys are case-sensitive

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val  = someDictionary["nepal"]
print(val)

When you run the program, the output will be:

nil

In the above program, there is no key nepal. So when you try to access the value of the key "nepal", you will get a nil value.

3. There is also a way to provide a default value if the value for a given key does not exist. Let's see this in example:

Example 12: Default value for non-existent key

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val  = someDictionary["nepal", default:"Not Found"]
print(val)

When you run the program, the output will be:

Not Found

In the above program, we have specified a value Not Found in the default parameter while accessing the dictionary. If the value does not exist for the key, the default value is returned otherwise the value is returned.

In our case, the key "nepal" isn't present, so the program returns Not Found.