Swift Dictionary default value


Greetings, traveler!

I don’t know about you, but I use dictionaries quite often. They are convenient tools for retrieving and storing data. The other day, I used a dictionary to store data arrays, updating them using a key. Check out this example.

var dictionary: [String: [String]] = [:]

dictionary["key"]?.append("value")

print(dictionary) // [:]

However, if the key we’re trying to append doesn’t exist in our dictionary, our action will be futile. To address this, we can implement a solution like this.

if dictionary["key"] != nil {
    dictionary["key"]?.append("value")
} else {
    dictionary["key"] = []
    dictionary["key"]?.append("value")
}

But it doesn’t look lovely.

The good news is that Apple has provided us with a convenient tool that will allow us to use the default value if the key is not in the dictionary. This method creates such a key and assigns it a default value.

dictionary["key", default: []].append("value")

Much better!

Conclusion

Swift is a language that offers a wide range of convenient features. Today, we have considered one of them in a little more detail. I hope you enjoyed this article. See you soon.