Why swift dictionary values are always optional?

Swift dictionaries are used to hold key-value pairs. We can use the key to access its corresponding values. For example :

var my_dict = ["one" : 1, "two" : 2, "three": 3]

For this dictionary, one, two, and three are keys and 1, 2 and 3 are values for these keys.

Using these keys, we can access the values.


This print statement will print the value for the key one :


As you can see, this is an optional value.

The reason is that it doesn’t know if the key exists or not in a dictionary. So, it returns an Optional value if the key exists, else it returns nil.