Swift-存储类型-字典

2016-11-19  本文已影响133人  Joker_King

字典存储相同类型的键之间的关联,以及没有定义顺序的集合中相同类型的值的关联。 每个值都与唯一键相关联,该键用作字典中该值的标识符。 与数组中的项不同,字典中的项没有指定的顺序。 当您需要基于其标识符查找值时,使用字典,与使用现实世界字典查找特定单词的定义大致相同。

字典类型速记语法

Swift字典的类型完全写为Dictionary <Key,Value>,其中Key是可用作字典键的值的类型,Value是字典为这些键存储的值的类型。

注意:字典键类型必须符合Hashable协议,如集合的值类型。

您还可以用简写形式将字典的类型写为[Key:Value]。 虽然这两种形式在功能上是相同的,但是缩写形式是优选的。

创建一个空字典

与数组一样,您可以使用初始化语法创建一个特定类型的空字典:

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
此示例创建一个类型为[Int:String]的空字典来存储整数值的可读名称。 它的键类型为Int,其值为String类型。

如果上下文已经提供了类型信息,则可以使用空字典字面量创建一个空字典,它以[:](一对方括号内的冒号)表示:

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers[17] = "sixteen"
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

用字面量创建一个字典

您还可以使用字典字面量初始化字典,该字典字面具有与前面的数组字面相似的语法。 字典字面量是一个将一个或多个键值对写为字典集合的简写方法。

键值对是键和值的组合。 在字典文字中,每个键值对中的键和值由冒号分隔。 键值对写为列表,用逗号分隔,并由一对方括号包围:

[key 1: value 1, key 2: value 2, key 3: value 3]

下面的示例创建一个字典来存储国际机场的名称。 在这本词典中,键是三个字母的国际航空运输协会代码,值是机场名称:

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

机场字典被声明为具有[String:String]类型,这意味着“键的类型为String,其值也为String类型的字典”。

机场字典用包含两个键值对的字典字面量初始化。 第一对具有键“YYZ”和值“Toronto Pearson”。 第二对具有“DUB”的键和“Dublin”的值。

这个字典字面值包含两个String:String对。 此键值类型与Airports变量声明(仅具有字符串键且仅包含字符串值)的类型匹配,因此允许分配字典文字作为初始化具有两个初始项的机场字典的方式。

与数组一样,如果您使用字典字面量化它的键和值具有一致的类型,则不必编写字典类型。 机场字典的初始化可以写成更短的形式:

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

因为字面量中的所有键都是彼此相同的类型,同样所有的值都是相同的类型,Swift可以推断[String:String]是用于机场字典的正确类型。

访问和修改词典

print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."

使用布尔isEmpty属性作为检查count属性是否等于0的快捷方式:

if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

您可以将新项目添加到具有下标语法的词典。 使用适当类型的新键作为下标索引,并分配适当类型的新值:

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

您还可以使用下标语法来更改与特定键相关联的值:

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

作为下标的替代,使用字典的updateValue(:forKey :)方法来设置或更新特定键的值。 与上面的下标示例类似,updateValue(:forKey :)方法为密钥(如果不存在)设置一个值,如果该密钥已经存在,则更新该值。 与下标不同,updateValue(_:forKey :)方法在执行更新后返回旧值。 这使您能够检查是否发生更新。

updateValue(_:forKey :)方法返回字典值类型的可选值。 对于存储字符串值的字典,例如,该方法返回类型为String?或“optional String”的值。 此可选值包含该键的旧值(如果在更新之前存在);如果没有值,则为nil:

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."

您还可以使用下标语法从字典中检索特定键的值。 因为可以请求没有值的键,字典的下标返回字典值类型的可选值。 如果字典包含所请求键的值,则下标返回包含该键的现有值的可选值。 否则,下标返回nil:

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."

您可以使用下标语法通过为该键分配值nil来从字典中删除键值对:

airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

或者,使用removeValue(forKey :)方法从字典中删除键值对。 此方法删除键值对(如果存在)并返回删除的值,或者如果没有值则返回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

如果您需要使用字典的键或值与一个接受Array实例的API,请使用keys或values属性初始化一个新数组:

let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]

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

Swift的字典类型没有定义的顺序。 要以特定顺序对字典的键或值进行迭代,请对其keys或values属性使用sorted()方法。

上一篇下一篇

猜你喜欢

热点阅读