Swift 字典的 updateValue:forKey
updateValue(_:forKey:)
Inserts or updates a value for a given key and returns the previous value for that key if one existed, or nil
if a previous value did not exist.
Declaration
mutating func updateValue(value: Value, forKey key: Key) -> Value?
Discussion
Use this method to insert or update a value for a given key, as an alternative to subscripting. This method returns a value of type Value?
—an optional with an underlying type of the dictionary’s Value
:
var dictionary = ["one": 1, "two": 2, "three": 3]
let previousValue = dictionary.updateValue(22, forKey: "two")
// previousValue is an optional integer with an underlying value of 2
In this example, previousValue
is of type Int?
, not Int
. Use optional binding to query and unwrap the return value if it is non-nil
:
if let unwrappedPreviousValue = dictionary.updateValue(33, forKey: "three") {
println("Replaced the previous value: \(unwrappedPreviousValue)")
} else {
println("Added a new value")
}
// prints "Replaced the previous value: 3"
Values in a dictionary can be updated using this method only if the dictionary is defined with the var
keyword (that is, if the dictionary is mutable):
let constantDictionary = ["one": 1, "two": 2, "three": 3]
constantDictionary.updateValue(4, forKey: "four")
// Error: cannot mutate a constant dictionary
if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
}
// The old value for DUB was Dublin.
/// Update the value stored in the dictionary for the given key, or, if they
/// key does not exist, add a new key-value pair to the dictionary.
/// Returns the value that was replaced, or `nil` if a new key-value pair
/// was added.
mutating func updateValue(value: Value, forKey key: Key) -> Value?
🏁返回的是旧值