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

0qx6xfy6  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(203)

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

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

ercv8c1e1#

您可以使用此选项:

dict[willRemoveKey] = nil

或以下内容:

dict.removeValueForKey(willRemoveKey)

唯一的区别是,第二个函数将返回删除的值(如果不存在,则返回nil)
雨燕3号

dict.removeValue(forKey: willRemoveKey)
bxjv4tth

bxjv4tth2#

雨燕5雨燕4雨燕3

x.removeValue(forKey: "MyUndesiredKey")
干杯

ufj5ltwl

ufj5ltwl3#

dict.removeValue(forKey: willRemoveKey)

或者,您可以使用下标语法:

dict[willRemoveKey] = nil
wyyhbhjk

wyyhbhjk4#

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"]

相关问题