May 10 2020

Dictionaries in Swift


In Swift, you have arrays which let you store multiple values of the same type in a variable or constant(only if you specified it as an array of any if you didn't, you can only have one type of value.). But, in Dictionaries it's different. You can have a dictionary that has 2 different data types, lets say String and Int, and still not having to specify that it is taking in a any data type.

This is because Dictionaries has 2 items for each element. A key and a value. This is always in the format: key : value. The first item, the key, is the item which is used to get the value of the element, it's used and identifier for the other item. ie, it can be used as the equivalent of de index of an element in an array. The value, as you might imagine, is the equivalent of an element in an array. This is what you store in the dictionary and what can be used.

How to use

You define a Dictionary as follows:

let cookingStake: [String: Int] = ["weight":500, "timePerSide":3]

In the code above, we declare a dictionary that takes in 2 items: an String and an Int. the first item, the key, is a string, where we specify the weight and time of cooking of a piece of stake.

You get the value of an element by typing the follows:


In our case, we would do this:


As you see, we specify a string to get a certain value. This helps when you don't know the index of a certain value, but still want to know the value. therefore you specify a string as the key, so that when you want to get a value, you can easily get it by just entering the string key.

Don’t forget that you can email me at for any questions, feedback or if you just wanted to say hi.