Exploring Swift Dictionaries: Key-Value Pair Mastery

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

by The Captain

on
May 21, 2024
Swift Dictionaries

Swift Dictionaries

Dictionaries in Swift are used to store key-value pairs. Each key in a dictionary must be unique, and the keys and values can be of any data type. Dictionaries are a powerful data structure in Swift that allows you to efficiently store and retrieve information based on a key.

Here is an example of how to create and use a dictionary in Swift:


// Creating a dictionary with String keys and Int values
var ages: [String: Int] = ["Alice": 30, "Bob": 25, "Charlie": 35]

// Adding a new key-value pair to the dictionary
ages["David"] = 40

// Accessing a value in the dictionary
let charliesAge = ages["Charlie"]

// Updating a value in the dictionary
ages["Bob"] = 26

// Removing a key-value pair from the dictionary
ages.removeValue(forKey: "Alice")

// Iterating over the key-value pairs in the dictionary
for (name, age) in ages {
    print("\(name) is \(age) years old")
}

In the code snippet above, we create a dictionary called "ages" that maps names (keys) to ages (values). We then add, access, update, and remove key-value pairs from the dictionary. Finally, we iterate over the dictionary to print out the names and ages of each person.

Dictionaries are commonly used in Swift to store and retrieve data in a structured way. They provide a convenient and efficient way to work with key-value pairs, making them a valuable tool for Swift developers.