Swift Dictionary Basics

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

by The Captain

April 11, 2024
Working with Swift Dictionaries

Working with Swift Dictionaries

Dictionaries in Swift allow you to store key-value pairs of data. They are similar to arrays, but instead of accessing elements by an index, you use a key to access values. In this tutorial, we will explore how to create, manipulate, and access data in dictionaries using Swift.

Creating a Dictionary

To create a dictionary in Swift, you can use the following syntax:

var fruitPrices: [String: Double] = ["Apple": 0.99, "Banana": 0.59, "Orange": 0.79]}
This line of code creates a dictionary called `fruitPrices` with keys of type `String` and values of type `Double`, and initializes it with three key-value pairs.

Accessing and Modifying Dictionary Values

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

print(fruitPrices["Apple"]) //Output: Optional(0.99)

fruitPrices["Banana"] = 0.69 //Modify the value of "Banana"}
In the code snippet above, we access the price of an apple using its key and modify the price of a banana.

Iterating Over Dictionary

You can iterate over a dictionary using a for loop:

for (fruit, price) in fruitPrices {
    print("\(fruit): $\(price)")
This loop iterates over each key-value pair in `fruitPrices` and prints the fruit name and its price.

Checking for Key Existence

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

if fruitPrices.contains(where: { $0.key == "Apple" }) {
    print("Apple is in the dictionary")
} else {
    print("Apple is not in the dictionary")
This code snippet checks if the key "Apple" exists in the dictionary `fruitPrices` and prints a message accordingly.