A dictionary is a memory that stores multiple data of the same type. Each value is associated with a unique key (key), which is used as the identifier for the value data in the dictionary. The data items in the dictionary are not in a specific order, unlike the data items in the array.
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] Dictiona Ry
Type inference writing [:]
namesofintegers["sixteen"// namesofintegers now contains 1 Key-value pairnamesofintegers = [:]// namesofintegers is once again an empty dictionary of Typ e [int:string]
Create dictionary literals
[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 modification
Count returns the key value logarithm of the dictionary
IsEmpty to determine if the dictionary is empty
airports["LHR""London Heathrow
if let OldValue = Airports.updatevalue ("Dublin Airport""DUB " { print ("Theoldvalue for DUB is \ (oldValue). ") " )}// Prints "The old value for DUB is Dublin.
Removevalueforkey (_:) Delete key-value pairs
if let Removedvalue = Airports.removevalueforkey ("DUB") { print ( " The removed airport ' s name is \ (removedvalue). " Else { print ("Theairports Dictionary does not contain a value For DUB. " )}// Prints "The removed airport ' s name is Dublin airport.
Traverse
for inch Airports { print ("\ (airportcode): \ (airportname)")}// yyz:toronto Pearson// Lhr:london Heathrow
forAirportcodeinchAirports.keys {print ("Airport code: \ (Airportcode)")}//Airport Code:yyz//Airport CODE:LHR forAirportnameinchairports.values {print ("Airport name: \ (airportname)")}//Airport Name:toronto Pearson//Airport Name:london Heathrow
Swift Learning Swift Programming Tour---collection type dictionaries (eight)