Swift Dictionary is used to store the key-value pairs and access the value by using the key. It is just like hash tables in other programming languages.
In Swift, a dictionary is a collection type that allows you to store key-value pairs. Each value in a dictionary is associated with a unique key, similar to a real-world dictionary where each word is associated with a definition. Here’s an explanation of dictionaries in Swift:
- Declaration: You can create an empty dictionary or initialize it with some initial values.
// Dictionary with initial values// Empty dictionary declaration
var emptyDictionary = [KeyType: ValueType]()
var dictionary = [“key1”: value1, “key2”: value2, “key3”: value3] - Accessing Elements: You can access elements in a dictionary using the keys.
let valueForKey2 = dictionary["key2"]
- Inserting and Updating: You can add new key-value pairs or update existing ones.
dictionary["newKey"] = newValue // Adds a new key-value pair
dictionary["key1"] = updatedValue // Updates the value for an existing key
- Removing Elements: You can remove key-value pairs from the dictionary.
dictionary["key3"] = nil // Removes the key-value pair for "key3"
- Iterating Over Elements: You can iterate over the key-value pairs in a dictionary.
for (key, value) in dictionary {
print("Key: \(key), Value: \(value)")
}
- Count: You can get the count of key-value pairs in a dictionary.
let count = dictionary.count
- Checking for Emptiness: You can check if a dictionary is empty.
if dictionary.isEmpty {
// Dictionary is empty
}
- Types: Both the key and value types must be hashable, meaning they must conform to the Hashable protocol. This allows Swift to efficiently look up values based on their keys.
var dictionary: [String: Int] = [:] // A dictionary with string keys and integer values
- Optional Values: Accessing a dictionary value by key returns an optional value because the key may not exist in the dictionary.
if let value = dictionary["key"] {
// Key exists, value contains the retrieved value
} else {
// Key doesn't exist
}
Dictionaries are commonly used when you need to store and retrieve values based on unique identifiers (keys). They provide efficient lookup times for retrieving values based on keys.