Swift 字典 removeAll()

removeAll() 方法会从字典中移除所有键值对。

示例

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

// remove all elements using removeAll() information.removeAll()
// print updated dictionary print(information) // Output: [:]

removeAll() 语法

removeAll() 方法的语法是:

dictionary.removeAll()

这里,dictionaryDictionary 类的一个对象。


removeAll() 参数

removeAll() 方法不接受任何参数。


removeAll() 返回值

  • removeAll() 方法不返回值。它仅从 dictionary 中移除键值对。

示例:Swift removeAll()

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

print("Before:", numbers)

// remove all key-value pairs using removeAll() numbers.removeAll()
// print updated dictionary print("After:", numbers)

输出

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

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

在这里,我们使用 removeAll() 方法从 numbers 中移除了所有键值对。

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

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

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

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