Use Dictionaries in Swift
Written by Team Kodeco
Dictionaries, also known as hash maps or associative arrays, are a powerful collection type in Swift for storing key-value pairs. The keys in a dictionary must be unique and can be of any hashable type, such as String
or Int
. The values can be of any type.
Here’s an example of creating and using a dictionary in Swift:
// Declare a dictionary of type [String: Int]
var ages = ["Alice": 25, "Bob": 30, "Charlie": 35]
// Add a new key-value pair to the dictionary
ages["Dave"] = 40
// Update the value for a key
ages["Bob"] = 32
// Access the value for a key
let bobAge = ages["Bob"] // 32
// Remove a key-value pair
ages.removeValue(forKey: "Charlie")
// Iterate over the key-value pairs
for (name, age) in ages {
print("\(name) is \(age) years old.")
}
Expected Output:
Alice is 25 years old.
Dave is 40 years old.
Bob is 32 years old.
As you can see from the output above, Dictionaries are unordered collections, meaning that the order of the key-value pairs may not be the same as the order in which they were added. If you need to maintain the order of the items, you may use an Array
and a Tuple
.
Create an Empty Dictionary
You can use the Dictionary
type for creating empty Dictionaries.
// Creating an empty dictionary
var emptyDict = [String: Int]()
var otherEmptyDict = Dictionary<String, Int>()