Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Dictionaries in Swift

Dictionaries in Swift

What is a Dictionary?

A dictionary in Swift is a collection type that stores key-value pairs. Each key in a dictionary must be unique, and it is used to access its corresponding value. The dictionary is a fundamental data structure for storing related information.

Creating a Dictionary

You can create a dictionary using the following syntax:

var myDictionary: [String: Int] = [:]

This creates an empty dictionary where keys are of type String and values are of type Int.

Initializing a Dictionary

Here’s how you can initialize a dictionary with some values:

var ages: [String: Int] = ["Alice": 30, "Bob": 25, "Charlie": 35]

Accessing Values

You can access the value associated with a specific key using subscript syntax:

let aliceAge = ages["Alice"]

The variable aliceAge will hold the value 30.

Adding and Updating Values

You can add a new key-value pair or update an existing key's value like this:

ages["David"] = 40 // Adds a new entry
ages["Alice"] = 31 // Updates Alice's age

Removing Values

To remove a key-value pair from a dictionary, you can use the removeValue(forKey:) method:

ages.removeValue(forKey: "Bob")

This will remove Bob from the dictionary.

Iterating Through a Dictionary

You can iterate through the keys and values of a dictionary using a for-in loop:

for (name, age) in ages {
print("\(name) is \(age) years old")
}

Conclusion

Dictionaries are a powerful way to store and manage data in Swift. They allow for efficient data retrieval based on unique keys. By understanding how to create, manipulate, and access dictionaries, you can effectively manage collections of related information in your applications.