我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
给出以下两本词典:
var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
下面是如何添加从dic2到dic1的所有项:
dic2.forEach {
dic1[$0.key] = $0.value
}
其他回答
Swift 3 - xcode 8.1
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
所以,你的字典包含:
字典[1:Hola, 2: Hello, 3: Aloha]
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)
您可以使用以下方式添加,并将Dictionary更改为NSMutableDictionary
dict["key"] = "value"
到目前为止,我发现的最好的方法是通过使用Swift的高阶函数之一来将数据追加到字典中。“减少”。遵循以下代码片段:
newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
@Dharmesh在你的情况下,
newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
请让我知道,如果你发现任何问题在使用上述语法。
在Swift中,如果你使用NSDictionary,你可以使用setValue:
dict.setValue("value", forKey: "key")