How to give default values for swift dictionary

A dictionary is used to store key-value pairs in Swift. We can access and modify any value using its key. But if we try to get any value using a key it always returns an Optional. For example,

var age_dict = ["Alex": 20, "Bob": 21]

print(age_dict["Bob"])

It will print :

Optional(21)

Also, if we try to access the value for a key that doesn’t exist, it will return nil. For the below example :

var age_dict = ["Alex": 20, "Bob": 21]

print(age_dict["Chandler"])

It will print nil .

But, we can give default value to a key in swift dictionary. Default value indicates that for that key, we will get that value if the value is not found.

var age_dict = ["Alex": 20, "Bob": 21]

print(age_dict["Chandler", default: 0])

It will return 0. Not an optional.

Returning an optional indicates that we will get one one value or we will get nil. But if we pass one default value, it is guaranteed that we will always get back one value. So, it is not optional.

var age_dict = ["Alex": 20, "Bob": 21]

print(age_dict["Alex", default: 0])

It will print 20. Without default, it will be Optional(20).