In Swift, dictionaries are incredibly useful data structures that allow you to store key-value pairs. They offer efficient lookups, updates, and deletions based on unique keys, making them ideal for tasks such as maintaining a collection of settings, counts, or translations.
A dictionary in Swift is defined using the syntax [KeyType: ValueType]
. Both the key and value types can be of any type, but the keys must be hashable.
var capitals: [String: String] = [
"France": "Paris",
"Germany": "Berlin",
"Japan": "Tokyo"
]
Accessing a value from a dictionary is done using subscript syntax.
let capitalOfFrance = capitals["France"]
print(capitalOfFrance) // Optional("Paris")
Note that the result is an optional because the key may not exist in the dictionary.
You can add or update a value using subscript notation.
capitals["Italy"] = "Rome" // Adds a new key-value pair
capitals["France"] = "Lyon" // Updates the value for the key "France"
To remove a key-value pair, simply set its value to nil
.
capitals["Germany"] = nil // Removes the key-value pair for "Germany"
You can iterate over the key-value pairs of a dictionary using a for-in loop.
for (country, capital) in capitals {
print("\(country): \(capital)")
}
To check whether a key exists in the dictionary, you can use the contains
method or check if the value is nil
.
if capitals.keys.contains("Japan") {
print("Capital of Japan is \(capitals["Japan"]!)")
}
Using the nil coalescing operator (??
), you can provide a default value when accessing a dictionary key.
let capitalOfItaly = capitals["Italy"] ?? "Unknown"
print(capitalOfItaly) // "Rome"
Dictionaries are a powerful tool in Swift for managing key-value data. By mastering basic operations like creation, modification, and iteration, you can effectively use dictionaries in many common programming scenarios.
```