翻譯能力有限,如有不對的地方,還請見諒!希望對Swift的學(xué)習(xí)者有所幫助,使用的編寫工具:JQNote? ??InNote(iPhone)
Dictionary是一個字典,存儲的是鍵值對,也是無序的。每一個值對應(yīng)唯一的key。寫作Dictionary, 其中key是Dictionary中一個鍵的類型,Value是Dictionary中與鍵對應(yīng)的存儲值的類型。Dictionary簡寫形式為 [Key : Value]
與集合類型Set類似,Dictionary中的Key類型必須遵守Hashable協(xié)議
創(chuàng)建一個空的Dictionary
跟Array一樣,你可以使用初始化語法創(chuàng)建一個空Dictionary:
var namesOfIntegers = [Int : String] ()
這個例子創(chuàng)建了一個空的[Int : String]字典類型,它的Key是Int類型,Value是String類型。如果代碼上下文已經(jīng)提供了類型信息,那么可以創(chuàng)建一個空的Dictionary,使用[ : ].
namesOfIntegers[16] = “Sixteen”
namesOfIntegers = [:].
也可以這樣創(chuàng)建一個Dictionary:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports聲明為一個[String: String]類型的Dictionary,也就是說,它的key是String類型,它的Value也是String類型。
與Array一樣,如果初始化值的類型是明確的,那么也可以不用寫[String: String]:
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
因?yàn)槌跏蓟得恳粋€key都是String,對應(yīng)每個Value也都是String,Swift會自動推斷該Dictionary的類型為[String: String].
獲取和修改Dictionary
跟Array一樣,你可以使用Dictionary的只讀屬性count來檢查它的存儲項數(shù)量
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.”
使用下標(biāo)索引語法來添加一個合適類型的key以及對應(yīng)的值,
airports["LHR"] = "London"
或者改變一個值
airports["LHR"] = "London Heathrow” “// the value for "LHR" has been changed to "London Heathrow”
也可以使用updateValue(_:forKey:)方法來更新某個特定key對應(yīng)的值, 如果不存在,會添加一個,如果存在,則更新。并且返回原來的舊值。
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.”
也可以使用下標(biāo)索引:
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.”
刪除一個鍵值對:
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:)
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.”
遍歷Dictionary
可以使用for-in循環(huán)來遍歷一個Dictionary,每一項返回一個(key,value)元組
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
如果想獲取Dictionary中所有的key,或者所有的value,可以使用它的keys和values屬性:
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
最后,Dictionary是無序的,如果想有序的遍歷一個Dictionary,用sorted()方法在它的keys和values屬性。