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:
1 2 3 4 5 6 |
let countriesAndCapitals = [“France”: “Paris”, “Germany”: “Berlin”, “Greece”: “Athens”, “Italy”: “Rome”] |
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:
1 2 3 |
let capital = countriesAndCapitals[“Greece”] |
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:
1 2 3 4 5 |
print(countriesAndCapitals[“Sweden”]) // Prints nil |
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:
1 2 3 4 5 6 |
print(countriesAndCapitals[“Sweden”, default: “Unknown capital city!”]) // Prints “Unknown capital city!” |
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!