如何从快速字典中删除键值对?

我想从字典中删除一个键-值对,如示例所示。

var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
78028 次浏览
dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil

You can use this:

dict[willRemoveKey] = nil

or this:

dict.removeValueForKey(willRemoveKey)

The only difference is that the second one will return the removed value (or nil if it didn't exist)

Swift 3

dict.removeValue(forKey: willRemoveKey)

Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers

var dict: [String: Any] = ["device": "iPhone", "os": "12.0", "model": "iPhone 12 Pro Max"]


if let index = dict.index(forKey: "device") {
dict.remove(at: index)
}


print(dict) // ["os": "12.0", "model": "iPhone 12 Pro Max"]