我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
要将一个新的键-值对追加到字典中,您只需设置键的值。如。
// 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”)
其他回答
(字符串:任何)
对于使用[String:Any]而不是Dictionary下面是扩展名
extension Dictionary where Key == String, Value == Any {
mutating func append(anotherDict:[String:Any]) {
for (key, value) in anotherDict {
self.updateValue(value, forKey: key)
}
}
}
给出以下两本词典:
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) }
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)
Swift 5快乐编码
var tempDicData = NSMutableDictionary()
for temp in answerList {
tempDicData.setValue("your value", forKey: "your key")
}