字典
字典是一種存儲多個相同類型的值的容器叠骑。每個值(value)都關(guān)聯(lián)唯一的鍵(key),鍵作為字典中的這個值數(shù)據(jù)的標識符沦童。和數(shù)組中的數(shù)據(jù)項不同谊惭,字典中的數(shù)據(jù)項并沒有具體順序。
- 字典類型簡化語法
Swift 的字典使用Dictionary<Key, Value>定義凌停,其中Key是字典中鍵的數(shù)據(jù)類型汽摹,Value是字典中對應于這些鍵所存儲值的數(shù)據(jù)類型。
我們也可以用[Key: Value]這樣簡化的形式去創(chuàng)建一個字典類型苦锨。
注意:
一個字典的Key類型必須遵循Hashable協(xié)議,就像Set的值類型趴泌。
初始化字典
創(chuàng)建一個空字典
- 使用構(gòu)造語法
var namesOfIntegers = [Int: String]()
// namesOfIntegers 是一個空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 現(xiàn)在包含一個鍵值對
namesOfIntegers = [:]
// namesOfIntegers 又成為了一個 [Int: String] 類型的空字典
- 用字典字面量創(chuàng)建字典
一個鍵值對是一個key和一個value的結(jié)合體舟舒。在字典字面量中,每一個鍵值對的鍵和值都由冒號分割嗜憔。這些鍵值對構(gòu)成一個列表秃励,其中這些鍵值對由方括號包含、由逗號分割:
[key 1: value 1, key 2: value 2, key 3: value 3]
//使用var聲明吉捶,表示可變的可以添加數(shù)據(jù)
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//airports字典被聲明為一種[String: String]類型夺鲜,這意味著這個字典的鍵和值都是String類型。
//簡短定義方法呐舔,因為Swift能夠根絕內(nèi)容數(shù)據(jù)推斷數(shù)據(jù)類型
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
訪問和修改字典
- 取某個字典的數(shù)據(jù)項數(shù)量:通過字典的只讀屬性count
print("The dictionary of airports contains \(airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(這個字典有兩個數(shù)據(jù)項)
- 判斷是否是空字典:使用布爾屬性isEmpty
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// 打印 "The airports dictionary is not empty."
- 使用下標來添加新的數(shù)據(jù)項
airports["LHR"] = "London"
// airports 字典現(xiàn)在有三個數(shù)據(jù)項
- 使用下標語法來改變特定鍵對應的值
airports["LHR"] = "London Heathrow"
// "LHR"對應的值 被改為 "London Heathrow
``
- 使用updateValue(_:forKey:)方法
updateValue(_:forKey:)方法可以設(shè)置或者更新特定鍵對應的值币励。就像上面所示的下標示例,updateValue(_:forKey:)方法在這個鍵不存在對應值的時候會設(shè)置新值或者在存在時更新已存在的值珊拼。和上面的下標方法不同的食呻,updateValue(_:forKey:)這個方法返回更新值之前的原值。這樣使得我們可以檢查更新是否成功澎现。updateValue(_:forKey:)方法會返回對應值的類型的可選值仅胞。
如果有值存在于更新前,則這個可選值包含了舊值剑辫,否則它將會是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."
- 使用下標語法來在字典中檢索特定鍵對應的值
因為有可能請求的鍵沒有對應的值存在,字典的下標訪問會返回對應值的類型的可選值妹蔽。如果這個字典包含請求鍵所對應的值椎眯,下標會返回一個包含這個存在值的可選值,否則將返回nil:
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 現(xiàn)在被移除了
- 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-in循環(huán)來遍歷某個字典中的鍵值對讹开。每一個字典中的數(shù)據(jù)項都以(key, value)元組形式返回盅视,并且我們可以使用臨時常量或者變量來分解這些元組
for (airportCode, airportName) in airports {
print("(airportCode): (airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
- 通過訪問keys或者values屬性
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屬性
如果我們只是需要使用某個字典的鍵集合或者值集合來作為某個接受Array實例的 API 的參數(shù),可以直接使用keys或者values屬性構(gòu)造一個新數(shù)組:
let airportCodes = String
// airportCodes 是 ["YYZ", "LHR"]
let airportNames = String
// airportNames 是 ["Toronto Pearson", "London Heathrow"]
Swift 的字典類型是無序集合類型旦万。為了以特定的順序遍歷字典的鍵或值闹击,可以對字典的keys或values屬性使用sorted()方法。
[原文出自51Swift轉(zhuǎn)載請保留原文鏈接](http://www.swift51.com/swift4.0)