0
0
Swiftprogramming~5 mins

Dictionary methods and default values in Swift

Choose your learning style9 modes available
Introduction

Dictionaries store pairs of keys and values. Methods help you add, find, or change these pairs easily. Default values keep your program safe when a key is missing.

You want to count how many times each word appears in a text.
You need to look up a phone number by a person's name.
You want to update a score for a player in a game.
You want to get a value but provide a backup if the key is not found.
Syntax
Swift
var dict = [KeyType: ValueType]()
dict[key] = value
let value = dict[key, default: defaultValue]
dict.updateValue(newValue, forKey: key)
dict.removeValue(forKey: key)

Use square brackets [] to get or set values by key.

The default value syntax helps avoid errors when a key is missing.

Examples
Change Alice's score to 12.
Swift
var scores = ["Alice": 10, "Bob": 8]
scores["Alice"] = 12
Get Bob's score or 0 if Bob is not in the dictionary.
Swift
let bobScore = scores["Bob", default: 0]
Add or update Charlie's score to 15.
Swift
scores.updateValue(15, forKey: "Charlie")
Remove Bob's score from the dictionary.
Swift
scores.removeValue(forKey: "Bob")
Sample Program

This program shows how to add, get with default, update, and remove items in a dictionary.

Swift
var inventory = ["apple": 3, "banana": 5]

// Add or update
inventory["orange"] = 2

// Get value with default
let appleCount = inventory["apple", default: 0]
let pearCount = inventory["pear", default: 0]

// Update value
inventory.updateValue(10, forKey: "banana")

// Remove value
inventory.removeValue(forKey: "apple")

print("Inventory: \(inventory)")
print("Apple count: \(appleCount)")
print("Pear count: \(pearCount)")
OutputSuccess
Important Notes

Using default values prevents your program from crashing when a key is missing.

updateValue returns the old value if it existed, which can be useful.

Removing a key that does not exist does nothing, so it's safe.

Summary

Dictionaries store key-value pairs and have useful methods to manage them.

Use default values to safely get values when keys might be missing.

Methods like updateValue and removeValue help change the dictionary easily.