Swift教程之集合类型详解

2020-01-08 22:48:14于海丽
复制代码
if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is (removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin International."

 

遍历字典

你可以使用一个for-in循环来遍历字典的键值对。字典中的每一个元素都会返回一个元祖(tuple),你可以在循环部分分解这个元祖,并用临时变量或者常量来储存它。

 

复制代码  
for (airportCode, airportName) in airports {
println("(airportCode): (airportName)")
}
// TYO: Tokyo
// LHR: London Heathrow
更多有关for-in 循环的信息, 参见 For Loops.
你也可以读取字典的keys属性或者values属性来遍历这个字典的键或值的集合。

 

 

复制代码  
for airportCode in airports.keys {
println("Airport code: (airportCode)")
}
// Airport code: TYO
// Airport code: LHR
for airportName in airports.values {
println("Airport name: (airportName)")
}
// Airport name: Tokyo
// Airport name: London Heathrow
如果你需要一个接口来创建一个字典的键或者值的数组实例,你可以使用keys或者values属性来初始化一个数值。

 

 

复制代码  
let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"]
let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]

 

注意

Swift中的字典类型是非序列化集合,如果你需要序列化取回键,值,或者键值对,遍历字典不具体叙述。

创建一个空字典

和字典一样,你可以使用确定类型的语法创建一个空的字典。

 

复制代码
var namesOfIntegers = Dictionary<Int, String>()
// namesOfIntegers 是一个空的 Dictionary<Int, String> 类型的字典