swift3.0之字典Dictionary

创建一个字典

var namesOfIntegers = [Int: String]()
// namesOfIntegers 是一个空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 [Int: String] 类型的空字典

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

访问和修改字典

///获取字典的数据项数量
print("The dictionary of airports contains \(airports.count) items.")
///检查count属性是否为0
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// 打印 "The airports dictionary is not empty."
///使用下标语法添加新的数据项
airports["LHR"] = "London"
// airports 字典现在有三个数据项

///使用下标语法来改变特定键对应的值
airports["LHR"] = "London Heathrow"
// "LHR"对应的值 被改为 "London Heathrow
///另一种下标法设置或者更新特定键对应的值
//如果有值存在于更新前,则这个可选值包含了旧值,否则它将会是nil
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// 输出 "The old value for DUB was Dublin."
///使用下标语法来在字典中检索特定键对应的值
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// 打印 "The name of the airport is Dublin Airport."
///使用下标语法来通过给某个键的对应值赋值为nil来从字典里移除一个键值对
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场, 删除它
airports["APL"] = nil
// APL 现在被移除了
///在字典中移除键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的值或者在没有值的情况下返回nil
if let removedValue = airports. removeValue(forKey: "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-in循环来遍历某个字典中的键值对
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
///直接使用字典中的keys或者values属性构造一个新数组
let airportCodes = [String](airports.keys)
// airportCodes 是 ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames 是 ["Toronto Pearson", "London Heathrow"]

转自:http://www.swift51.com/swift3.0.html

猜你喜欢

转载自blog.csdn.net/amberoot/article/details/87913480
今日推荐