swift Dictionary

字典是一種存儲多個相同類型的值的容器。每個值(value)都關(guān)聯(lián)唯一的鍵(key),鍵作為字典中的這個值數(shù)據(jù)的標(biāo)識符。字典中的數(shù)據(jù)項并沒有具體順序,我們在需要通過標(biāo)識符(鍵)訪問數(shù)據(jù)的時候使用字典。

創(chuàng)建一個空字典

var namesOfIntegers = [Int: String]()

// namesOfIntegers 是一個空的 [Int: String] 字典

訪問和修改字典

和數(shù)組一樣,我們可以通過字典的只讀屬性 來獲取某個字典的數(shù)據(jù)項數(shù)量:

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

print("The dictionary of airports contains \(airports.count) items.")

// 打印 "The dictionary of airports contains 2 items."(這個字典有兩個數(shù)據(jù)項)

使用布爾屬性isEmpty來快捷地檢查字典的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."

我們也可以在字典中使用下標(biāo)語法來添加新的數(shù)據(jù)項

airports["LHR"] ="London"? // airports 字典現(xiàn)在有三個數(shù)據(jù)項

我們也可以使用下標(biāo)語法來改變特定鍵對應(yīng)的值:

airports["LHR"] = "London Heathrow"? // "LHR"對應(yīng)的值 被改為 "London Heathrow

我們還可以使用下標(biāo)語法來通過給某個鍵的對應(yīng)值賦值為nil來從字典里移除一個鍵值對:

airports["LHR"] = nil? // LHR 現(xiàn)在被移除了

此外,removeValueForKey(_:)方法也可以用來在字典中移除鍵值對

字典遍歷

我們可以使用for-in循環(huán)來遍歷某個字典中的鍵值對。每一個字典中的數(shù)據(jù)項都以(key, value)元組形式返回,并且我們可以使用臨時常量或者變量來分解這些元組:

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

如果我們只是需要使用某個字典的鍵集合或者值集合來作為某個接受 實例的 API 的參數(shù),可以直接使用k或者 屬性構(gòu)造一個新數(shù)組:

let airportCodes = [String](airports.keys)

// airportCodes 是 ["YYZ", "LHR"]

let airportNames = [String](airports.values)

// airportNames 是 ["Toronto Pearson", "London Heathrow"]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容