閱讀766 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Swift字典

字典初始化

 

基本語法:

 

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

3]

 var   airports:    Dictionary<String,       String>    = ["TYO": "Tokyo", "DUB":"Dublin"]

 字典追加元素

 var   airports:    Dictionary<String,       String>    = ["TYO": "Tokyo", "DUB":"Dublin"] airports["LHR"] = "London"

 println("The dictionary of airports contains

\(airports.count) items.")

 

字典刪除元素

 

通過 removeValueForKey(key)方法刪除

 var airports: Dictionary<String, String> =

["TYO": "Tokyo", "DUB": "Dublin"]

 

if         let          removedValue                   =

airports.removeValueForKey("DUB") {

 

println("The removed airport's nameis \(removedValue).")

 

} else {

 

println("The airports dictionary doesnot contain a value forDUB.")

 

}

 

字典長度

 

使用 count 屬性。

 var   airports:    Dictionary<String,       String>    = ["TYO": "Tokyo", "DUB":"Dublin"]

 println("The dictionary of airports contains

\(airports.count) items.")

字典遍曆

 

1.遍曆方法

 var airports = ["TYO": "Tokyo", "DUB": "Dublin"]

 for (airportCode,airportName) in airports {

 println("\(airportCode): \(airportName)")

 }

 

2.遍曆鍵和值

 

for airportCode in airports.keys {

 println("Airport code: \(airportCode)")

 }

 for airportName in airports.values {

 println("Airport name: \(airportName)")

 }

 

 

 

獲得鍵或值的數組:

let airportCodes= Array(airports.keys)

 // airportCodes is ["TYO", "LHR"]

 

let airportNames = Array(airports.values)

  // airportNamesis ["Tokyo","London Heathrow"]

 

Swift交流討論論壇論壇:https://www.cocoagame.net

歡迎加入Swift技術交流群:362298485

 



最後更新:2017-04-03 07:57:12

  上一篇:go 【AllJoyn框架-01】連接PC與Arduino Due開發板
  下一篇:go C++11中的mutex, lock,condition variable實現分析