我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
字典updateValue更新字典中现有键的值,如果键不存在,则添加新的键-值对。
的例子,
var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
结果- - - - - -
▿ : 2 elements
- key : "userId"
- value : 866
▿ : 2 elements
- key : "otherNotes"
- value : "Hello"
其他回答
如果你想修改或更新NSDictionary那么 首先,将它类型转换为NSMutableDictionary
let newdictionary = NSDictionary as NSMutableDictionary
然后简单地使用
newdictionary.setValue(value: AnyObject?, forKey: String)
给出以下两本词典:
var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
下面是如何添加从dic2到dic1的所有项:
dic2.forEach {
dic1[$0.key] = $0.value
}
我添加了字典扩展
extension Dictionary {
func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
var result = self
dict.forEach { key, value in result[key] = value }
return result
}
}
你可以像这样使用克隆
newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }
斯威夫特 3+
向Dictionary分配新值的示例。你需要声明它为NSMutableDictionary:
var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
添加新元素只需设置:
listParameters["your parameter"] = value