我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
您可以使用以下方式添加,并将Dictionary更改为NSMutableDictionary
dict["key"] = "value"
其他回答
我知道这可能会很晚,但它可能会对某人有用。 因此,在swift中将键值对追加到字典中,你可以使用updateValue(value:, forKey:)方法,如下所示:
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
Swift 5快乐编码
var tempDicData = NSMutableDictionary()
for temp in answerList {
tempDicData.setValue("your value", forKey: "your key")
}
从Swift 5开始,以下代码收集工作。
// main dict to start with
var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]
// dict(s) to be added to main dict
let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
let myDictUpdated : Dictionary = [ 5 : "lmn"]
let myDictToBeMapped : Dictionary = [ 6 : "opq"]
myDict[3]="fgh"
myDict.updateValue("ijk", forKey: 4)
myDict.merge(myDictToMergeWith){(current, _) in current}
print(myDict)
myDict.merge(myDictUpdated){(_, new) in new}
print(myDict)
myDictToBeMapped.map {
myDict[$0.0] = $0.1
}
print(myDict)
给出以下两本词典:
var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
下面是如何添加从dic2到dic1的所有项:
dic2.forEach {
dic1[$0.key] = $0.value
}
如果你的字典是Int到String,你可以简单地做:
dict[3] = "efg"
如果你的意思是向字典的值中添加元素,一个可能的解决方案是:
var dict = Dictionary<String, Array<Int>>()
dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)