字典初始化數組
基本語法:spa
[key 1: value 1, key 2: value 2, key 3: value.net
3]code
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB":"Dublin"]orm
字典追加元素rem
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB":"Dublin"] airports["LHR"] = "London"it
println("The dictionary of airports containsio
\(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交流討論論壇論壇:http://www.cocoagame.net
歡迎加入Swift技術交流羣:362298485