浏览 1056 次
锁定老帖子 主题:Swift字典
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-06-20  

字典初始化

 

基本语法:

 

[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) iairports {

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

 }

 

2.遍历键和值

 

for airportCode iairports.keys {

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

 }

 for airportName iairports.values {

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

 }

 

 

 

获得键或值的数组:

leairportCodes= Array(airports.keys)

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

 

leairportNames = Array(airports.values)

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

 

 

Swift交流讨论论坛论坛:http://www.cocoagame.net

欢迎加入Swift技术交流群:362298485

 

论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics