我有一个简单的字典,它的定义如下:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

现在我想在这个字典中添加一个元素:3:"efg"

我如何能追加3:“efg”到这个现有的字典?


当前回答

var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)

其他回答

如果你的字典是Int到String,你可以简单地做:

dict[3] = "efg"

如果你的意思是向字典的值中添加元素,一个可能的解决方案是:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)

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]

如果你想修改或更新NSDictionary那么 首先,将它类型转换为NSMutableDictionary

let newdictionary = NSDictionary as NSMutableDictionary

然后简单地使用

 newdictionary.setValue(value: AnyObject?, forKey: String)

我添加了字典扩展

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) }
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)