Swift 字典 updateValue()

updateValue() 方法用于更新字典中给定键的值。

示例

// create a dictionary with two elements
var information = ["Charlie": 54, "Harvey": 34]

// update value of "Charlie" to 57 information.updateValue(57, forKey: "Charlie")
// print updated dictionary print(information) // Output: ["Charlie": 57, "Harvey": 34]

updateValue() 语法

updateValue() 方法的语法是

dictionary.updateValue(new_value, forKey: key)

这里,dictionaryDictionary 类的一个对象。


updateValue() 参数

updateValue() 方法接受一个参数

  • new_value - 要添加的新值
  • key - 要更新其值的键。

注意:如果键尚不存在,则会创建新的键值对。


updateValue() 返回值

  • updateValue() 方法返回被替换的值。

注意: 如果添加了新的键值对,则该方法返回 nil


示例 1:Swift updateValue()

// create a dictionary with two elements
var marks = ["Sabby": 78, "Nick": 59]

print("Marks Before:", marks)

// update value of "Nick" to 67 marks.updateValue(67, forKey: "Nick")
// print updated dictionary print("Marks After:", marks)

输出

Marks Before: ["Nick": 59, "Sabby": 78]
Marks After: ["Nick": 67, "Sabby": 78]

示例 2:创建新的键值对

// create a dictionary with two elements
var marks = ["Sabby": 78, "Nick": 59]

print("Before:", marks)

// associate value 45 to new key Sazz marks.updateValue(45,forKey: "Sazz")
// print updated dictionary print("After:", marks)

输出

Before: ["Sabby": 78, "Nick": 59]
After: ["Sabby": 78, "Nick": 59, "Sazz": 45]

这里,由于 marks 字典中不存在名为 "Sazz" 的键,因此创建了新的键值对。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战