Swift – Dictionary | Associative Array | Mapping Type

We will learn about dictionary data type in swift.

What : A dictionary is a way to organise data/information in form of key and value. Dictionary is also known as “Associative Array”or “Mapping Type”.

When : You can use dictionary when you want to pass information around. The best example is API/web service response (A.K.A. JSON) which uses dictionary. You also need dictionary data type in iOS programming when you want to pass data around your view/screens/classes etc.

Variable Declaration : Simplest form to create a dictionary is :

There are couple of more another ways of initialising dictionary in swift, for example:

We will consider simplest form of dictionary creation in below examples:

Example 1 : Let’s create a constant dictionary named student whose key and value both are String data type:

We can not change a constant dictionary, student dictionary is immutable. See example and attached attached screen shot :

Example 2 : Let’s create a mutable dictionary named library whose key and value are String and int data type respectively:

Example 3 : Let’s create a mutable dictionary named powerOfThree whose key and value both are Int data type respectively:

Example 4 : Let’s try to access value for key 2.

Example 5 : Lets’s see example of adding a new key value pair in the dictionary.  

Example 6 : Lets see  some more properties of dictionary:

Some more basic example of dictionary from my playground:

Note : To get all keys and all value of dictionary in form of array we have to convert LazyMapCollection to Array:

Example :



2 thoughts on “Swift – Dictionary | Associative Array | Mapping Type”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.