Swift – Create Dictionary

Welcome to Swift Tutorial. In this tutorial, we will learn how to create a dictionary with (key, value) pairs in Swift programming.

Dictionaries are used to store a collection of (key, value) pairs. In a dictionary, you can only insert (key, value) pairs whose key is unique in the dictionary.

Dictionary can be created in two ways. They are

1. Create an empty Dictionary

To create an empty dictionary in Swift, use the following syntax,

</>
Copy
var myDict = [KeyType: ValueType]()

where

myDict is the identifier used for this dictionary

KeyType is the datatype of the key in (key, value)

ValueType is the datatype of the value in (key, value)

Examples

In the following example, we create a dictionary that has a key of Int type and value of Int type.

</>
Copy
var myDict = [Int: Int]()

In the following example, we create a dictionary that has a key of Int type and value of String type.

</>
Copy
var myDict = [String: String]()

In the following example, we create a dictionary that has a key of String type and value of String type.

</>
Copy
var myDict = [String: String]()

2. Create a Dictionary with Initial Values

To create a dictionary with initial values, use the following syntax,

</>
Copy
var myDict:[KeyType: ValueType] = [key1:value1, key2:value2, .. , keyN:valueN]

where

myDict is the identifier used for this dictionary

KeyType is the datatype of the key in (key, value)

ValueType is the datatype of the value in (key, value)

keyN:valueN pairs are separated by a comma.

Examples

In the following example, we create a dictionary with some initial values that has a key of Int type and value of Int type.

</>
Copy
var myDict:[Int:Int] = [1:25, 2:54, 3:87]

In the following example, we create a dictionary that has a key of Int type and value of String type.

</>
Copy
var myDict:[Int:String] = [22:"Swift Tutorial", 12:"Tutorial Kart"]

In the following example, we create a dictionary that has a key of String type and value of String type.

</>
Copy
var myDict:[String:String] = ["as12":"Swift Tutorial", "mm24":"Tutorial Kart"]

Conclusion

In this Swift Tutorial, we have learned to create an empty dictionary and a dictionary with some initial values with the help of Example Swift programs.