Swift--字典的了解

字典存储时,key和value值的类型都是固定的,且都是无序的。

1.字典类型的缩写语法

在swift中,字典的完整格式如下:

Dictionary<Key, Value>

 注意:字典的key类型必须符合 哈希算法。

字典的缩写格式如下:

[Key: Value]

 虽然完整格式和缩写格式都可以,但是下面介绍字典时主要是以缩写格式为主。

2.创建一个空的字典

当初始化一个空的字典时,可以直接初始化其key和value值的类型,如下:

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

 如下的例子,可以理解为:key为Int类型,value为string类型。

如果字典的元素可以判断出其key和value的值,那么可以创建一个格式为 [:] 的空字典:

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

3. 创建一个字典并初始化字典的值

在字典中,key和value的值以“:”号区分开,每一对key和value的值用逗号隔开。

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

 如下的例子:

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

 正如数组一样,如果创建一个字典并初始化字典的key和value的值时,不需要写字典中key和value值的类型。如下:

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

 从上面的例子中,swift可以推断出,该字典的key和value的类型都是string类型。

4.字典的取值与修改

你可以用字典的相关方法、属性和下标语法对字典进行取值和修改的操作。

<1>可以用只读属性count来获取字典元素的个数;

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

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

 <3>用下标语法添加一个新的元素,往字典添加一个新的key和value值,如下:

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:)的方法来添加或者修改字典key中的value值。如果这个key值存在,就更新这个key的value值;如果这个key值不存在,就添加。与下标不同的是,updateValue(_:forKey:)方法在执行更新后返回key对应的旧值,这使您能够检查是否发生了更新。这个旧值是可选值,如果更新的这个key值存在的话,这个可选值就是更新前key对应value的值,否者的话,返回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."

 可以用下标语言来获取一个字典中key对应的value值,因为key可能不存在在字典中,所以该返回值为可选值,如果key值存在,就返回对应的value值;如果不存在,就返回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."

 可以通过把key对应的value值设置为nil的方法来删除key-value的值;

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:)的方法删除字典中的key-value值,调用这个方法时,如果key值存在的话,返回的是remove的值,如果不存在就返回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."

5.遍历字典

可以用for-in遍历字典中的key-value值,每一个元素以(key, vlue)的元组返回;您可以将tuple的成员分解为临时常量或变量,作为迭代的一部分;

for (airportCode, airportName) in airports {
    print("(airportCode): (airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

 用字典中的keys 和 values 属性来获取字典中所有的属性或者value值;

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

  如果需要将字典中所有的key和value值,以字典的形式返回的话,可以用字典中的keys和values属性来初始化一个新的数组:

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

6. 字典是无序的,如果需要对字典排序的话,请对字典的keys 和 values 属性 用sorted() 的方法。

原文地址:https://www.cnblogs.com/lyz0925/p/7847378.html