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() 的方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM