Creating Dictionaries in Swift 🎯

beginner
24 min

Creating Dictionaries in Swift 🎯

Welcome to this comprehensive guide on creating dictionaries in Swift! This tutorial is designed to help both beginners and intermediates understand the concept from scratch.

What is a Dictionary? 📝

In Swift, a dictionary is a collection of key-value pairs. It's similar to an array, but instead of storing elements at index positions, it stores values associated with specific keys. This makes dictionaries great for storing data that needs to be accessed using keys, like a database or a user profile.

Declaring a Dictionary 💡

To declare a dictionary, you use the Dictionary type and specify the key and value types inside square brackets. Here's a simple example:

swift
var myDictionary: [String: Int] = ["apple": 10, "banana": 20]

In this example, myDictionary is a dictionary that holds keys of type String and values of type Int. The keys are "apple" and "banana," and their corresponding values are 10 and 20, respectively.

Accessing and Modifying Dictionary Entries 💡

You can access a dictionary's value using its key like this:

swift
print(myDictionary["apple"]) // Output: 10

To modify a dictionary entry, you can assign a new value to the key:

swift
myDictionary["apple"] = 20 print(myDictionary["apple"]) // Output: 20

Adding and Removing Entries 💡

To add a new entry, you can use the subscript syntax:

swift
myDictionary["orange"] = 30 print(myDictionary) // Output: ["apple": 20, "banana": 20, "orange": 30]

To remove an entry, you can use the removeValue(forKey:) method:

swift
myDictionary.removeValue(forKey: "banana") print(myDictionary) // Output: ["apple": 20, "orange": 30]

Iterating Through a Dictionary 💡

You can iterate through a dictionary using a for-in loop:

swift
for (key, value) in myDictionary { print("\(key): \(value)") }

This will output:

apple: 20 orange: 30

Quiz 🎯

Quick Quiz
Question 1 of 1

What type is used to declare a dictionary in Swift?

Quick Quiz
Question 1 of 1

How can you access a dictionary's value using its key in Swift?

That's it for this lesson on creating dictionaries in Swift! In the next lesson, we'll dive deeper into working with dictionaries, including sorting, merging, and filtering. Stay tuned! 📝