字典是一種存儲相同類型多重數據的存儲器。每一個值(value)都關聯獨特的鍵(key),鍵做爲字典中的這個值數據的標識符。和數組中的數據項不一樣,字典中的數據項並無具體順序。數組
字典寫做Dictionary<Key, Value>。也能夠寫做[Key: Value]spa
建立空字典code
var namesOfIntegers = [Int: String]() // namesOfIntegers is an empty [Int: String] dictionary
類型推斷寫做[:]blog
namesOfIntegers[16] = "sixteen" // namesOfIntegers now contains 1 key-value pair namesOfIntegers = [:] // namesOfIntegers is once again an empty dictionary of type [Int: String]
建立字典字面量rem
[key 1: value 1, key 2: value 2, key 3: value 3]io
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
類型推斷寫做class
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
訪問和修改date
count返回字典的鍵值對數遍歷
isEmpty判斷字典是否爲空數據
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(_:)刪除鍵值對
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.
遍歷
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