As dictionaries are one of Swift's three primary collection types, knowing how to work with dictionaries is a big part of knowing how to program in Swift.
var addresses: Dictionary<String, String> = ["The Munsters": "1313 Mockingbird Lane", "The Simpsons": "742 Evergreen Terrace", "Buffy Summers": "1630 Revello Drive"]
var sequences: [String: [Int]] = ["Euler's totient": [1, 1, 2, 2, 4, 2, 6, 4], "Lazy caterer": [1, 2, 4, 7, 11, 16, 22, 29, 37], "Carmichael": [561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841]]
let constants: = ["pi": 3.14159, "e": 2.71828, "phi": 1.618033, "avogadro": 6.02214076e22]
[Int: String](), or, if the type can be determined from the context, as just a pair of square brackets surrounding a colon, [:].Dictionary<K, V> or [K: V] where K is the type of the keys in the dictionary and V is the type of the values.addresses["The Simpsons"].nil is returned if a requested key is not present in the dictionary.let e: Double = constants["e", default: 0]
// => 2.71828
let hoagie: [Int] = sequences["Hoagie", default: []]
// => []
let betty = addresses["Betty Cooper", default: "Address unknown"]
// => "Address unknown"
var).sorted(by:) method.for (name, address) in addresses {
print("\(name) lives at \(address)")
}
// prints out:
// Betty Cooper lives at 111 Queens Ave.
// The Munsters lives at 1313 Mockingbird Lane
// The Simpsons lives at 742 Evergreen Terrace
// Buffy Summers lives at 1630 Revello Drive
The other methods available for working with dictionaries can be seen in the Apple Swift API documentation.