Default Value in Swift Dictionary
Table of Contents
When you try to access a value from a dictionary with a key that doesn't exist, you will get nil
.
This makes perfect sense since nil
represent "the absence of a valid object".
But sometimes, you might want to get a default value if the key isn't found. Swift dictionary has an easy way to do that.
Access dictionary with a default value
To get a default value instead of nil
when the key isn't found, you can specify the default value along with the subscription key, dict["key", default: "default value"]
.
Let's say we have a dictionary that stores the number of times we see each alphabet.
let counter: [String: Int] = [
"a": 1,
"b": 2,
"c": 3
]
print(counter["d"])
// nil
print(counter["d", default: 0])
// 0
Reading the value of the key "d" would return a nil
, counter["d"]
.
0
makes more sense than nil
in this case. We can specify the default value using this form counter["d", default: 0]
.
This might not seem useful since you can define the default value using Nil-coalescing operator.
counter["d", default: 0]
counter["d"] ?? 0
But I think this feature shrine when you try to assign the value.
You can easily support sarunw.com by checking out this sponsor.
Localization Buddy: Easiest way to localize and update App Store metadata.
Assign dictionary with a default value
Here is an example where we count the number of strings in an array, source
.
Without using the default value, we might need to do something similar to this.
let source = ["a", "b", "c", "s", "w", "a", "a", "s"]
var counter: [String: Int] = [:]
for c in source {
// 1
if let count = counter[c] {
counter[c] = count + 1
} else {
counter[c] = 1
}
}
print(counter)
// ["s": 2, "a": 3, "w": 1, "b": 1, "c": 1]
1 We must check whether the value exists and act accordingly.
If we use a dictionary default value, we can remove the if-let
part.
let source = ["a", "b", "c", "s", "w", "a", "a", "s"]
var counter: [String: Int] = [:]
for c in source {
// 1
counter[c, default: 0] += 1
}
print(counter)
// ["s": 2, "a": 3, "c": 1, "b": 1, "w": 1]
Read more article about Swift, Dictionary, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to hide a Navigation Back button in SwiftUI
Learn a simple way to hide a back button in SwiftUI. And whether we should hide it or not.
How to convert Radians to Degrees in Swift
In this article, we will learn different ways to convert Radians to Degrees in iOS.