Swift Dictionaries Basics

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

by The Captain

on
May 1, 2024
Working with Dictionaries in Swift

Working with Dictionaries in Swift

Dictionaries are a fundamental data structure in Swift that allow you to store key-value pairs. In this tutorial, we will explore how to create, modify, and access dictionaries in Swift.

Creating a Dictionary

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

let myDictionary: [String: Int] = ["apple": 5, "banana": 3, "orange": 7]

In this example, we have created a dictionary where the keys are of type String and the values are of type Int.

Accessing and Modifying a Dictionary

You can access and modify the values in a dictionary by using the keys. For example:

myDictionary["apple"] = 10 let numberOfOranges = myDictionary["orange"]

In this code snippet, we are updating the value associated with the key "apple" and then retrieving the value associated with the key "orange".

Iterating Over a Dictionary

You can iterate over the key-value pairs in a dictionary using a for-in loop. Here's an example:

for (key, value) in myDictionary { print("Key: \(key), Value: \(value)") }

Conclusion

Dictionaries are a powerful data structure in Swift that allow you to store and retrieve key-value pairs efficiently. By understanding how to work with dictionaries, you can build more complex and flexible applications in Swift.