【Swift學習】Swift編程之旅---集合類型之Dictionaries(八),swiftdictionaries

來源:互聯網
上載者:User

【Swift學習】Swift編程之旅---集合類型之Dictionaries(八),swiftdictionaries

  字典是一種儲存相同類型多重資料的儲存空間。每個值(value)都關聯獨特的鍵(key),鍵作為字典中的這個值資料的標識符。和數組中的資料項目不同,字典中的資料項目並沒有具體順序。

  字典寫作Dictionary<Key, Value>。也可以寫作[Key: Value]

 

  建立空字典

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

 

  類型推斷寫作[:]

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

 

 

  建立字典字面量

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

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

 

  類型推斷寫作

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

 

 

  訪問和修改

  count返回字典的索引值對數

  isEmpty判斷字典是否為空白

  

airports["LHR"] = "London Heathrow

 

 

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.

 

 

  removeValueForKey(_:)刪除索引值對  

if let removedValue = airports.removeValueForKey("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 (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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.