复制代码
airports["LHR"] = "London Heathrow"
//"LHR" 的值已经被改变为 "London Heathrow"
同样, 使用字典的updateValue(forKey:) 方法去设置或者更新一个特定键的值 . 和上面的下标例子一样, updateValue(forKey:) 方法如果键不存在则会设置它的值,如果键存在则会更新它的值, 和下标不一样是, updateValue(forKey:) 方法 如果更新时,会返回原来旧的值rThis enables you to 可以使用这个来判断是否发生了更新。
复制代码
updateValue(forKey:) 方法返回一个和字典的值相同类型的可选值. 例如,如果字典的值的类型时String,则会返回String? 或者叫“可选String“,这个可选值包含一个如果值发生更新的旧值和如果值不存在的nil值。
if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") {
println("The old value for DUB was (oldValue).")
}
// prints "The old value for DUB was Dublin."
你也可以使用下标语法通过特定的键去读取一个值。因为如果他的值不存在的时候,可以返回他的键,字典的下标语法会返回一个字典的值的类型的可选值。如果字典中的键包含对应的值,这字典下标语法会返回这个键所对应的值,否则返回nil
复制代码if let airportName = airports["DUB"] {
println("The name of the airport is (airportName).")
} else {
println("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin International."
你可以使用下标语法把他的值分配为nil,来移除这个键值对。
复制代码
airports["APL"] = "Apple International"
// "Apple International" 不是 APL的真实机场,所以删除它
airports["APL"] = nil
// APL 已经从字典中被移除
同样,从一个字典中移除一个键值对可以使用removeValueForKey方法,这个方法如果存在键所对应的值,则移除一个键值对,并返回被移除的值,否则返回nil。








