Dictionaries are a fundamental collection type in Swift, providing a way to store key-value pairs. They offer fast lookup and flexible data organization, making them essential for many programming tasks.
In Swift, you can create a dictionary using square brackets [:]
. Here's a simple example:
var fruits = ["apple": 5, "banana": 3, "orange": 2]
This creates a dictionary where fruit names are keys and their quantities are values.
To access a value, use its corresponding key:
let appleCount = fruits["apple"] // Optional(5)
Note that dictionary access returns an optional, as the key might not exist. You can modify values using subscript syntax:
fruits["banana"] = 4 // Updates banana count to 4
fruits["grape"] = 6 // Adds a new key-value pair
fruits.keys.contains("apple")
fruits.removeValue(forKey: "orange")
fruits.count
for (fruit, quantity) in fruits {
print("\(fruit): \(quantity)")
}
Swift's type safety extends to dictionaries. The compiler infers types from initialization, but you can also explicitly declare types:
var scores: [String: Int] = [:]
This creates an empty dictionary with String keys and Int values.
Dictionaries can be combined with other Swift features for more powerful operations:
filter()
and mapValues()
.Understanding dictionaries is crucial for effective Swift programming. They provide a versatile way to organize and access data, making them indispensable in many applications.