[Swift learning] Swift programming tour-collection type Dictionaries (8), swiftdictionaries
A dictionary is a storage that stores multiple types of data. Each value is associated with a unique key as the identifier of the value data in the dictionary. Unlike the data items in the array, the data items in the dictionary are not in specific order.
Dictionary writing Dictionary <Key, Value>. You can also write [Key: Value]
Create an empty dictionary
var namesOfIntegers = [Int: String]()// namesOfIntegers is an empty [Int: String] dictionary
Type inference writing [:]
namesOfIntegers[16] = "sixteen"// namesOfIntegers now contains 1 key-value pairnamesOfIntegers = [:]// namesOfIntegers is once again an empty dictionary of type [Int: String]
Create dictionary literal
[Key 1: value 1, key 2: value 2, key 3: value 3]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
Type inference writing
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
Access and modify
Count returns the logarithm of the dictionary key value.
IsEmpty determines whether the dictionary is empty
airports["LHR"] = "London Heathrow
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") { print("The old value for DUB was \(oldValue).")}// Prints "The old value for DUB was Dublin.
RemoveValueForKey (_ :) deletes a key-Value Pair
if let removedValue = airports.removeValueForKey("DUB") { print("The removed airport's name is \(removedValue).")} else { print("The airports dictionary does not contain a value for DUB.")}// Prints "The removed airport's name is Dublin Airport.
Traversal
for (airportCode, airportName) in airports { print("\(airportCode): \(airportName)")}// YYZ: Toronto Pearson// LHR: London Heathrow
for airportCode in airports.keys { print("Airport code: \(airportCode)")}// Airport code: YYZ// Airport code: LHR for airportName in airports.values { print("Airport name: \(airportName)")}// Airport name: Toronto Pearson// Airport name: London Heathrow