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

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"

其他回答

我添加了字典扩展

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

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

// 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”)

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

dict[3] = "efg"

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

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

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

在Swift中,如果你使用NSDictionary,你可以使用setValue:

dict.setValue("value", forKey: "key")

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