Working with Dictionaries in Swift: Basics and Operations

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 23, 2024

Working with Dictionaries in Swift

Dictionaries are a fundamental data structure in Swift that allow you to store key-value pairs. This tutorial will cover how to work with dictionaries in Swift, including declaring, accessing, modifying, and iterating over dictionaries.

Declaring a Dictionary

In Swift, you can declare a dictionary using the following syntax:

var studentGrades = ["Alice": 95, "Bob": 87, "Charlie": 92]}

This declares a dictionary `studentGrades` with keys "Alice", "Bob", and "Charlie" mapping to their respective integer values.

Accessing and Modifying Values

You can access and modify values in a dictionary using subscript notation:

// Accessing values
let aliceGrade = studentGrades["Alice"]

// Modifying values
studentGrades["Bob"] = 90}

Iterating Over a Dictionary

To iterate over a dictionary, you can use a for-in loop with key-value pairs:

for (name, grade) in studentGrades {
    print("\(name) has a grade of \(grade)")
}

Checking for Key Existence

You can use the `contains` method to check if a key exists in a dictionary:

if studentGrades.contains(where: { $0.key == "Alice" }) {
    print("Alice's grade is present in the dictionary")
}

Conclusion

In this tutorial, we covered the basics of working with dictionaries in Swift, including declaring, accessing, modifying, iterating, and checking for key existence. Dictionaries are a powerful tool for mapping keys to values and are commonly used in Swift programming.