How is a dictionary structured in Swift?
sobes.tech AI
Answer from AI
A Dictionary in Swift is a collection of unordered key-value pairs.
Main characteristics:
- Unordered: The order of elements is not guaranteed.
- Unique keys: Each key in the dictionary must be unique.
- Hashable keys: The key type must be hashable (i.e., conform to the
Hashableprotocol). Types likeString,Int,Double,Bool, and most structures are hashable by default. - Type safety: The dictionary is strictly typed, both for keys and values.
- Storage: Implemented based on a hash table, which provides high efficiency for insert, delete, and access operations by key (average O(1)).
Creating a dictionary:
// Empty dictionary
var emptyDictionary: [String: Int] = [:]
// Dictionary with initial values
let cities: [String: String] = [
"London": "UK",
"Paris": "France",
"Tokyo": "Japan"
]
Access and modification:
// Access by key (returns Optional)
let country = cities["Paris"] // Optional("France")
// Add or update a value
var scores: [String: Int] = ["Alice": 100, "Bob": 85]
scores["Charlie"] = 90 // Adding
scores["Alice"] = 105 // Updating
// Remove a value
scores["Bob"] = nil // Removing the element with key "Bob"
Iteration:
for (city, country) in cities {
print("\(city) is in \(country)")
}
for city in cities.keys {
print("City: \(city)")
}
for country in cities.values {
print("Country: \(country)")
}
Internal structure (generally):
Swift uses a modified hash table implementation. When inserting a key-value pair:
- The hash value of the key is computed.
- The hash value is used to determine the "bucket" where the element should be placed.
- If there are already elements in the bucket, a collision resolution mechanism (e.g., chaining or open addressing) is used to find an appropriate spot.
Most operations (insertion, deletion, access) have performance close to O(1) with uniform hash distribution and few collisions. In the worst case (all hashes land in one bucket), performance can degrade to O(n), but this is rare for good hash functions and sufficiently large hash tables. When the number of elements increases, the dictionary may perform rehashing, increasing the internal structure's size to maintain efficiency, which can be a relatively costly operation.