Swift 字典的 updateValue:forKey

本文介绍如何使用updateValue(_:forKey:)方法在Swift中更新字典值,包括基本用法、返回值解释及实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

 

?返回的是旧值

转载于:https://www.cnblogs.com/deanlee/p/4432138.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值