Exploring Dictionaries in Swift: Create, Access, Modify, and Iterate

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

by The Captain

on
March 25, 2024

Working with Dictionaries in Swift

Dictionaries are a powerful data structure in Swift that allow you to store key-value pairs. They can be used to store information in a structured way and provide efficient lookups for data retrieval. Let's explore how to work with dictionaries in Swift.

Creating a Dictionary

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

var myDictionary = [String: String]()}
This creates an empty dictionary with keys and values of type String. You can also initialize a dictionary with key-value pairs like this:
var airportCodes = ["JFK": "John F. Kennedy International Airport",
                    "LAX": "Los Angeles International Airport",
                    "ORD": "Chicago O'Hare International Airport"]}

Accessing and Modifying Dictionary Values

To access a value in a dictionary, you can use the key to look up the corresponding value. For example:

let airportName = airportCodes["JFK"]}
This will retrieve the value "John F. Kennedy International Airport" for the key "JFK". You can also modify values in a dictionary by assigning a new value to a key:
airportCodes["LAX"] = "LAX International Airport"}

Iterating Over a Dictionary

You can iterate over a dictionary using a for loop and access both the key and value of each key-value pair:

for (code, name) in airportCodes {
    print("Airport code: \(code), Name: \(name)")
}
This will print out each key-value pair in the dictionary.

Checking for Key Existence

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

if airportCodes.contains(where: { $0.key == "JFK" }) {
    print("Key exists in dictionary")
}
This will print "Key exists in dictionary" if the key "JFK" is present in the dictionary.

Conclusion

Dictionaries are a versatile data structure in Swift that allow you to store and retrieve key-value pairs efficiently. By understanding how to create, access, modify, iterate over, and check for key existence in dictionaries, you can leverage their power in your Swift applications.