Swift by Example: Dictionaries
Understanding Swift dictionaries with this code example showing key-value pair storage, optional value access, safe unwrapping with if-let, adding and updating entries, removing keys by setting nil, and iterating over dictionary contents.
Code
// Creating a dictionary
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// Accessing values (returns an Optional)
if let airportName = airports["DUB"] {
print("The name of the airport is (airportName).")
} else {
print("That airport is not in the dictionary.")
}
// Adding/Updating
airports["LHR"] = "London Heathrow"
airports["YYZ"] = "Toronto Pearson International"
// Removing
airports["DUB"] = nil
// Iterating
for (code, name) in airports {
print("(code): (name)")
}Explanation
Dictionaries store associations between keys and values. Each key must be unique. Like arrays, dictionaries are strongly typed. The syntax [KeyType: ValueType] is used to define the type.
Accessing a dictionary using a key returns an Optional value. This is because the key might not exist in the dictionary. You should safely unwrap the result using if let or provide a default value using the nil-coalescing operator ??.
You can add or update a value by assigning to a key using subscript syntax. Assigning nil to a key removes that key-value pair from the dictionary. Dictionaries are unordered, so iterating over them does not guarantee any specific order.
Code Breakdown
[String: String] defines a dictionary with string keys and string values.if let airportName = airports["DUB"] safely unwraps the optional value.airports["LHR"] = "London Heathrow" adds a new key-value pair.airports["DUB"] = nil removes the key-value pair from the dictionary.
