我想从字典中删除一个键值对,就像例子中一样。
var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
我想从字典中删除一个键值对,就像例子中一样。
var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
你可以使用这个:
dict[willRemoveKey] = nil
或者这样:
dict.removeValueForKey(willRemoveKey)
唯一的区别是第二个将返回已删除的值(如果它存在)或者 nil(如果它不存在)
dict.removeValue(forKey: willRemoveKey)
Swift 5, Swift 4 和 Swift 3:
x.removeValue(forKey: "MyUndesiredKey")
祝好!
dict.removeValue(forKey: willRemoveKey)
您可以使用下标语法:dict[willRemoveKey] = nil
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"]
let dict = ["k1": "v1" , "k2": "v2"]
for ( k, _) in dict{
dict.removeValue(forKey: k)
}
dict.removeValue(willRemoveKey)
,因为看起来.removeValueForKey
已经被重命名了 - 感谢您的帮助! - Coty Embrynil
将总是删除该键。要在可选值类型的字典中分配真正的nil
值,请分配.some(nil)
。 - BallpointBen