创建空字典
import UIKit
// 创建空字典
var namesOfIntegers = [Int : String]()
// 插入值
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]
创建有初始值的字典
// 创建有初始值的字典
var airports : [String : String] = ["YYZ" : "Toronto Pearson", "DUB" : "Dublin"]
print("The airports dictionary contains \(airports.count) items")
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The ariports dictionray is not empty")
}
插入新键值对
// 插入新键值对
airports["LHR"] = "London"
print(airports)
console log 如下
修改
// 修改
airports["LHR"] = "London Heathrow"
print(airports)
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue)")
}
print(airports)
console log 如下
访问
// 访问
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName)")
} else {
print("That airport is not in the airports dictionary")
}
console log 如下
移除键对应的值
// 移除
airports["APL"] = "Apple International"
print(airports)
airports["APL"] = nil
print(airports)
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.")
}
print(airports)
console log 如下
遍历
// 遍历
for (airportCode, airportName) in airports {
print("\(airportCode) : \(airportName)")
}
for airportCode in airports.keys {
print("Airport code :\(airportCode)")
}
for airportName in airports.values {
print("Airport name :\(airportName)")
}
let airportCodes = [String](airports.keys)
print(airportCodes)
let airportNames = [String](airports.values)
print(airportNames)
console log 如下