Swift Dictionary

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

by The Captain

on
June 12, 2023

Working with Dictionary in Swift

Dictionary in Swift is a powerful data structure that allows us to store data as key-value pairs. It is similar to an array but instead of accessing elements using an index, we access them using a unique key. In this tutorial, we will explore how to create, access, and modify a dictionary in Swift.

Creating a Dictionary in Swift

In Swift, we can create a dictionary using the following syntax:

var myDictionary = [Key: Value]()}

Here, the `Key` and `Value` can be of any data type. For example, if we want to create a dictionary that stores the number of apples each person has, we can create it like this:

var apples = [String: Int]()}

This creates an empty dictionary that can hold `Int` values against `String` keys.

Adding Values to a Dictionary

We can add a key-value pair to our dictionary using the following syntax:

myDictionary[key] = value}

For example, to add an entry to our `apples` dictionary with key `"John"` and value `5`, we can write:

apples["John"] = 5}

We can also add multiple elements to our dictionary at once by using the `updateValue(_:forKey:)` method. This method adds the key-value pair to our dictionary if it does not already exist and returns the previous value associated with the key (if any). For example:

apples.updateValue(3, forKey: "David")
apples.updateValue(2, forKey: "Emily")}

Accessing Values from a Dictionary

We can access the value associated with a specific key in our dictionary by using the key as an index:

let johnApples = apples["John"]}

This will give us the value associated with the key `"John"`, which is `5`.

If we are not sure whether a key exists in our dictionary or not, we can use optional binding to safely unwrap the value returned by the `subscript` method:

if let emilyApples = apples["Emily"] {
    // do something with emilyApples...
}

This code will only execute if the key `"Emily"` exists in our dictionary. Otherwise, the optional binding will fail and the code inside the `if` block will not execute.

Iterating over a Dictionary

We can loop through all the key-value pairs in our dictionary using a `for-in` loop:

for (key, value) in apples {
    print("\(key) has \(value) apples")
}

This will print:

John has 5 apples
David has 3 apples
Emily has 2 apples}

Summary

Dictionaries are an important data structure used in Swift for storing and retrieving data as key-value pairs. We can use the `[]` operator to add or retrieve a value from the dictionary, or use the `updateValue(_:forKey:)` method to add multiple entries at once. We can loop through all the key-value pairs in a dictionary using a `for-in` loop.