Home » Swift Dictionary

Swift Dictionary

by Online Tutorials Library

Swift Dictionary

A Swift dictionary is a simple container that can contain multiple data as key-value pair in an unordered way.

Swift dictionary is used instead of array when you want to look up value with some identifier in the collection. Suppose, we have to search the capital city of country. In this case, we 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. Here, we have paired a country to its capital city.

Dictionary declaration in Swift

Declaring an empty dictionary

To create an empty dictionary, we specify the key:value Data type inside square brackets [].

Example:

Or

Output:

[:]  

Declaring a dictionary with some values

Output:

["c": 30, "d": 40, "g": 70, "b": 20, "a": 10, "f": 60, "h": 80, "i": 90, "e": 50]  

In the above program, we have not declared the type explicitly but we initialize with some default elements. The element is in key:value pair where key is of type String and value is of Int type.

Creating Dictionary from two arrays

We can also create dictionary from arrays.

Example:

Output:

["India": "New Delhi", "United Kingdom": "London", "Pakistan": "Islamabad"]  

Access Dictionary elements in Swift

We can access elements of a Swift dictionary by including key of the value we want to access within square brackets immediately after the name of the dictionary.

Example:

Output:

Optional(30)  Optional(60)  

Access Dictionary elements in Swift using for-in loop

Example:

Output:

key:h value:80  key:d value:40  key:a value:10  key:g value:70  key:e value:50  key:b value:20  key:c value:30  key:f value:60  key:i value:90  

Modify dictionary elements in Swift

We can add a new element in a Swift dictionary by using a new key as index and assign to a new value.

Example:

Output:

["Germany": "Berlin", "China": "Beijing", "USA": "Washington D.C.", "India": "New Delhi"]  

Changing elements in Dictionary

Example:

Output:

["USA": "Washington D.C.", "China": "Beijing", "India": "NEW DELHI"]  

Next TopicSwift Sets

You may also like