Hallo vrienden, Leo hier. The topic today is how to have a Default Value from Dictionary in Swift when the searched key is not found.

We’ll discuss some interesting and somewhat kind confusing default value getters from dictionaries. Using dictionaries in Swift is easy and straightforward but when you come across some not-so-usual situations, things may be confusing. So stay tuned for this tip and let’s code!

But first…


Painting of The Day

The painting chosen was 1932 called Old Books by Catherine Mary Wood. She was a British painter and unfortunately with very little info about her online.

The painting was chosen because dictionaries were books in the old days.


The problem – Default Value from Dictionary

You want to when getting value from a dictionary if you don’t find any, you have a default value from it.

Imagine you have a dictionary with the name and age of a person, you can initialize it in various ways:

var nameAgeDict: Dictionary<String,Int> = [:]
var nameAgeDict2: [String:Int] = [:]
var nameAgeDict3 = [String:Int]()
var nameAgeDict4 = Dictionary<String,Int>()
var nameAgeDict5 = ["Leo":30]
var nameAgeDict6: Dictionary<String,Int> = Dictionary<String,Int>()

Once you initialized it, you can set new keys and values:

nameAgeDict["Tales"] = 12 

You can print it resulting in:

Default Value from Dictionary in Swift guide image

But what if you want to check if a person exists and if not add that person to the dictionary with a default value?


Using Default Parameter in Dictionary Subscript

You can use the default parameter of the Dictionary subscript like this:

for name in ["Leo","Ana","John"] {
    nameAgeDict[name] = nameAgeDict[name,default: -1]

Now the print statement will be:

Default Value from Dictionary in Swift guide image 2

Great! Now we have default values when are sure to have all the names in our dictionary. Now let’s dive a little deeper into this syntax.

With the subscript default parameter, you sure have a value for a key. This also can be used with the *+=* function to count things individually, like how many of each letter are in some string:

let message = "Hello my friends, how are you doing?!"
var letterCounts: [Character: Int] = [:]
for character in message {
    letterCounts[character, default: 0] += 1 // mark 1


The mark one means: Search for the character in the dictionary. If you find add one to it, if not use the default value plus one and create an entry in the dictionary with the character being the key.

Resulting in a neatly separated dictionary, notice that whitespaces are considered too:

Default Value from Dictionary in Swift guide image 3

One curious thing about the subscript default parameter is that works magically with the += and -= functions/operator. Analyze the code below:

nameAgeDict["Tales", default: 0] += 1 // mark 1
nameAgeDict["Tales"] = nameAgeDict["Tales", default: 0] + 1 // mark 2

The result of both statements is the same.
Mark 1 was already explained. But if mark 1 works… How can mark 2 work as well? What is the real return of the subscript default parameter?

@inlinable public subscript(key: Key, default defaultValue: @autoclosure () -> Value) -> Value

So the return is the Value in our case is Int… but wait… now the mark 1 doesn’t make sense. If the return of the subscript is a value, the += function should at most sum zero to one how does it know it should create a dictionary entry for the Key provided if the result of the subscript is a Value?

Well, I couldn’t find an answer. If anyone reading this knows how and why mark 1 and mark 2 work instead of the “compiler magic” response please leave a comment below.

This is the end.


Summary – Default Value from Dictionary in Swift

That’s it. Today we’ve explored some details and behaviors of dictionary default subscript and also some “add and assign” magic.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for reading and… That’s all folks.

Credits: image