![iOS 12 Programming for Beginners](https://wfqqreader-1252317822.image.myqcloud.com/cover/76/36699076/b_36699076.jpg)
Creating a dictionary
The traditional way of creating a dictionary is to first declare it as a dictionary and then, inside angle brackets, declare a type for the key and value. Let's create our first dictionary inside Playgrounds:
![](https://epubservercos.yuewen.com/2E52D1/19470383901517806/epubprivate/OEBPS/Images/4d83637f-bbda-4195-8908-f01fd16082c1.png?sign=1738964774-NGpoPjUqa60r06Ye9K3BVoMHSAWhS8Xn-0-cf20f36c8e1bd4bb7d2467225c84c9af)
The immutable dictionary we created earlier has a string data type for both its key and value. We have multiple ways to create a dictionary. Let's look at another by adding the following to Playgrounds:
let dictSecondExample = [String: Int]()
Your code should now look like this:
![](https://epubservercos.yuewen.com/2E52D1/19470383901517806/epubprivate/OEBPS/Images/ce6021e3-5a5f-4837-bffd-82757ff40d65.png?sign=1738964774-KXKUOxHIn6GctGZHlYt5ZDPMsAWaKtkl-0-b9e2552e66a32cac79723f5641cc2122)
In this latest example, we created another immutable dictionary, with its key having a string data type and its value having an int data type.
If we wanted to use our pizza diagram, the key would have a string data type and the value would have a double data type. Let's create this dictionary in Playgrounds, but, this time, we will make it a mutable dictionary and give it an initial value:
var dictThirdExample = Dictionary<String, Double>(dictionaryLiteral: ("veggie", 14.99), ("meat", 16.99))
Your code should now look like this:
![](https://epubservercos.yuewen.com/2E52D1/19470383901517806/epubprivate/OEBPS/Images/817d7922-18b9-4ee6-bde8-00bbecf8447d.png?sign=1738964774-Q5EuAo92x6WdpebdrrKfXSZzJ5wBax9g-0-639e38ecf8813e6e63994290de58cd76)
The preceding example is just one way of creating a dictionary for our pizza diagram example. Let's look at a much more common method using type inference:
var dictPizzas = ["veggie": 14.99]
Once you add this to your code, your code should look something like this:
![](https://epubservercos.yuewen.com/2E52D1/19470383901517806/epubprivate/OEBPS/Images/46ef272f-88e8-44e8-8ed8-5f0c0b26105e.png?sign=1738964774-aiyZ1NHhPu2JuY1PUdPutarJAm9hOm8h-0-54857a02f8a96eef7bdd1140e54a3650)
The preceding is a much simpler way of creating a dictionary with an initial value. When initializing a dictionary, it can have any number of items. In our case, we are starting off with just one.
Now, let's look at how we can add more pizzas to our dictionary.