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

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

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

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


当前回答

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")

其他回答

字典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"

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]

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

要将一个新的键-值对追加到字典中,您只需设置键的值。如。

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]
 
// Add a new key with a value

dict["email"] = "john.doe@email.com"

print(dict)

输出——>“姓”:“母鹿”、“名称”:“约翰”,“电子邮件”:“john.doe.com”)