Swift 字典 removeValue()

removeValue() 方法会从字典中移除指定的键及其关联的值。

示例

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

// remove certain key-value pair using removeValue() information.removeValue(forKey: "Charlie")
// print updated dictionary print(information) // Output: ["Harvey": 34]

removeValue() 语法

removeValue() 方法的语法是:

dictionary.removeValue(forKey: key)

这里,dictionaryDictionary 类的一个对象。


removeValue() 参数

removeValue() 方法接受一个参数:

  • key - 要移除的键及其关联的值。

removeValue() 返回值

  • removeValue() 方法会返回从 dictionary 中移除的值。

示例:Swift removeValue()

// create a dictionary with three elements
var numbers = ["one": 1, "Two": 2, "Three": 3]

print("Before:", numbers)

// remove "Three" and it's associated value 3 numbers.removeValue(forKey: "Three")
// print updated dictionary print("After:", numbers)

输出

Before: ["Two": 2, "one": 1, "Three": 3]
After: ["Two": 2, "one": 1]

在上面的示例中,我们创建了一个名为 numbers 的字典,其中包含三个键值对。

在这里,我们使用 removeValue() 方法移除了名为 "Three" 的键及其关联的值 **3**。

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

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

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

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