跳到主要内容

Swift 字典 removeValue() 方法

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

示例

// 创建一个包含两个元素的字典
var information = ["Charlie": 54, "Harvey": 34]

// 使用 removeValue() 移除指定的键-值对
information.removeValue(forKey: "Charlie")

// 打印更新后的字典
print(information)

// 输出: ["Harvey": 34]

removeValue() 语法

removeValue() 方法的语法如下:

dictionary.removeValue(forKey: key)

这里,dictionaryDictionary 类的对象。

removeValue() 参数

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

  • key - 要移除的键以及与之关联的值。

removeValue() 返回值

  • removeValue() 方法返回从字典中移除的值。

示例:Swift removeValue()

// 创建一个包含三个元素的字典
var numbers = ["one": 1, "Two": 2, "Three": 3]

print("Before:", numbers)

// 移除 "Three" 及其关联的值 3
numbers.removeValue(forKey: "Three")

// 打印更新后的字典
print("After:", numbers)

输出

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

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

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