我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
从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)
其他回答
添加新元素只需设置:
listParameters["your parameter"] = value
在Swift中,如果你使用NSDictionary,你可以使用setValue:
dict.setValue("value", forKey: "key")
在字典中没有附加数据的函数。您只需根据现有字典中的新键分配值。它将自动向字典中添加值。
var param = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)
输出是这样的
["名称":“阿罗哈”,“用户”:“阿罗哈2”,“问题”:“你是我的”吗?”)
到目前为止,我发现的最好的方法是通过使用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 5快乐编码
var tempDicData = NSMutableDictionary()
for temp in answerList {
tempDicData.setValue("your value", forKey: "your key")
}