Default Value in Swift Dictionaries

May 14th, 2021

⏱ Reading Time: 2 mins

Dictionaries in Swift are collections that store key-value pairs of data. For example, the following demonstrates a dictionary that keeps a few countries and their capital cities:

Keys match to countries, and values match to capital cities. In this particular example both keys and values are strings. To read a value from the dictionary we use the key like so:

The capital constant will get the value “Athens”, because the key exists in the dictionary.

However, if a key does not exist in a dictionary, the returned value will be nil. For instance, trying to print the capital city of Sweden will show nil; Sweden is not a key in the dictionary:

A nil value resulting from a missing key in a dictionary is quite often a convenient value, but not always. There are times where we want to get an actual value and not nil, no matter if the key exists or not in the dictionary.

The solution to that is to provide a default value right when we are asking the dictionary for a value using a key. All we need to do is to provide one more argument with the default value that will be returned back instead of a real one if the key does not exist in the dictionary:

The above ensures that even if the key is missing, no nil value will come back, and that saves us from the hassle of messing with optionals.

If you were not using dictionaries with default values up until now, then consider start doing so if it makes sense to the logic of your program. You might manage to make your coding tasks a bit easier and simpler. Thanks for reading!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on

    We respect your privacy. Unsubscribe at any time.