Dictionaries Introduction 🎯

beginner
5 min

Dictionaries Introduction 🎯

Welcome to Swift Dictionaries tutorial! In this lesson, we'll explore one of the essential data structures in Swift - Dictionaries. By the end of this tutorial, you'll have a strong understanding of how to work with Dictionaries, creating, accessing, and manipulating data.

What is a Dictionary? 📝

A Dictionary is a collection of key-value pairs, where each key uniquely identifies a value. It's a flexible data structure that allows you to store and retrieve data quickly, making it perfect for real-world projects.

Creating a Dictionary 💡

To create a Dictionary in Swift, you use the Dictionary data type and specify the key-value pairs inside curly braces {}. Here's a simple example:

swift
var myDictionary: [String: Int] = ["Apples": 5, "Oranges": 3]

In this example, we've created a Dictionary called myDictionary, which holds the keys "Apples" and "Oranges", each associated with a value (the number of fruits). The type of the keys and values is String and Int, respectively.

Accessing and Manipulating Data ✅

You can access a value in a Dictionary using the dot notation:

swift
print(myDictionary["Apples"]) // Output: 5

To update a value, you can reassign the value for the specific key:

swift
myDictionary["Apples"] = 6

Now, if you print the myDictionary again, the value for "Apples" will be 6.

Looping through Dictionaries 💡

You can loop through a Dictionary using the for-in loop:

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

This will print all key-value pairs in the Dictionary.

Quiz 🎯

Stay tuned for the next lessons on Dictionaries, where we'll cover more advanced features like iterating over keys and values separately, adding and removing items, and more! 🚀