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

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

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

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


当前回答

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 dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

下面是如何添加从dic2到dic1的所有项:

dic2.forEach {
   dic1[$0.key] = $0.value
}
For whoever reading this for swift 5.1+

  // 1. Using updateValue to update the given key or add new if doesn't exist


    var dictionary = [Int:String]()    
    dictionary.updateValue("egf", forKey: 3)



 // 2. Using a dictionary[key]

    var dictionary = [Int:String]()    
    dictionary[key] = "value"



 // 3. Using subscript and mutating append for the value

    var dictionary = [Int:[String]]()

    dictionary[key, default: ["val"]].append("value")

Swift 5快乐编码

var tempDicData = NSMutableDictionary()

for temp in answerList {
    tempDicData.setValue("your value", forKey: "your key")
}

我知道这可能会很晚,但它可能会对某人有用。 因此,在swift中将键值对追加到字典中,你可以使用updateValue(value:, forKey:)方法,如下所示:

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)

斯威夫特 3+

向Dictionary分配新值的示例。你需要声明它为NSMutableDictionary:

var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)