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
函数会返回包含一个字典值类型的可选值。对于存储 String 值的字典,这个函数会返回一个 String?或者“可选 String”类型的值。如果值存在,则这个可选值值等于被替换的值,否则将会是 nil。

 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?

 

🏁返回的是旧值

posted on 2015-04-16 15:01  DeanLee  阅读(1304)  评论(0编辑  收藏  举报