Dictionaries & Sets
Swift provides Dictionaries for key-value pairs and Sets for unique values.
Dictionaries
A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering.
Creating Dictionaries
var airPorts = ["YYZ": "Toronto", "DUB": "Dublin"]
var emptyDict: [String: String] = [:]
// Use the 'Any' type when your dictionary holds multiple different value types
var userProfile: [String: Any] = ["name": "Alice", "age": 28, "isActive": true]NOTE
Mixed Key Types > By default, all keys in a dictionary must be the exact same data type. If you need to mix key types (such as using both text and numbers as keys), you must explicitly declare the key type as AnyHashable.
var mixedKeys: [AnyHashable: String] = [
"status": "Active",
404: "Not Found"
]Accessing
You retrieve values using their key. Since a key might not exist, dictionaries return an Optional. You can safely handle missing keys using a default value directly inside the subscript.
print(airPorts["YYZ"] ?? "Unknown") // Using nil-coalescing
print(airPorts["JFK", default: "Not Found"]) // Using a default valueModifying
You can add, update, or remove items using their keys. Assigning nil to a key removes it completely from the dictionary.
airPorts["LHR"] = "London" // Adding or updating
airPorts["LHR"] = nil // Removing a keyIterating over Dictionaries
for (key, value) in airPorts {
print("\(key): \(value)")
}You can iterate over only the keys or only the values of the dictionaries as well, as shown below:
for key in airPorts.keys {
print(key)
}
for value in airPorts.values {
print(value)
}Sets
A set stores unique values of the same type in a collection with no defined ordering.
Creating Sets
var genres: Set<String> = ["Rock", "Classical", "Jazz"]
// Empty Sets
var emptySet = Set<Int>()
var anotherEmptySet: Set<String> = [] // Type must be explicit to use []Removing Duplicates from an Array
Because sets guarantee unique values, you can pass an array with repeated elements into a set to quickly strip out all duplicates. You can then convert it back into an array.
let duplicateNumbers = [1, 2, 2, 3, 4, 4, 5]
let uniqueNumbers = Array(Set(duplicateNumbers))
print(uniqueNumbers) // [2, 4, 5, 1, 3] (the order may vary)Common Operations
Sets are highly efficient for membership tests.
genres.insert("Hip Hop")
genres.remove("Rock")
if genres.contains("Jazz") {
print("I love Jazz!")
}Set Operations
Swift sets support standard mathematical operations:
.intersection(_:): Values in both sets..union(_:): All values from both sets..subtracting(_:): Values in one set but not the other..symmetricDifference(_:): Values in either set, but not both.
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
// Union: All values from both (1, 3, 5, 7, 9, 0, 2, 4, 6, 8)
oddDigits.union(evenDigits).sorted()
// Intersection: Values common to both (3, 5, 7)
oddDigits.intersection(singleDigitPrimeNumbers).sorted()
// Subtracting: Values in first but not in second (1, 9)
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// Symmetric Difference: Values in either but not both (1, 2, 9)
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()