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
swift
var airPorts = ["YYZ": "Toronto", "DUB": "Dublin"]
var emptyDict: [String: String] = [:]Accessing and Modifying
swift
print(airPorts["YYZ"] ?? "Unknown") // Subscripting returns an Optional
airPorts["LHR"] = "London" // Adding/Updating
airPorts["LHR"] = nil // Removing a keyIterating over Dictionaries
swift
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:
swift
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
swift
var genres: Set<String> = ["Rock", "Classical", "Jazz"]
// Empty Sets
var emptySet = Set<Int>()
var anotherEmptySet: Set<String> = [] // Type must be explicit to use []Common Operations
Sets are highly efficient for membership tests.
swift
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.
swift
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()