1. 程式人生 > >Swift字典

Swift字典

pan 技術交流 style family lin 通過 doesn not height

字典初始化

基本的語法:

[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", "D

UB": "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



Swift字典