Swift字典的removeAll()方法
removeAll()
方法会移除字典中的所有键-值对。
示例
// 创建一个包含两个元素的字典
var information = ["Charlie": 54, "Harvey": 34]
// 使用 removeAll() 移除所有元素
information.removeAll()
// 打印更新后的字典
print(information)
// 输出: [:]
removeAll() 语法
removeAll()
方法的语法如下:
dictionary.removeAll()
这里,dictionary
是 Dictionary
类的对象。
removeAll() 参数
removeAll()
方法不接受任何参数。
removeAll() 返回值
removeAll()
方法不返回任何值。它只会从字典中移除键-值对。
示例:Swift removeAll()
// 创建一个包含三个元素的字典
var numbers = ["one": 1, "Two": 2, "Three": 3]
print("Before:", numbers)
// 使用 removeAll() 移除所有键-值对
numbers.removeAll()
// 打印更新后的字典
print("After:", numbers)
输出
Before: ["Two": 2, "one": 1, "Three": 3]
After: [:]
在上面的示例中,我们创建了一个名为 numbers
的字典,其中包含三个键-值对。
在这里,我们使用 removeAll()
方法来移除 numbers
中的所有键-值对。