我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
您可以使用以下方式添加,并将Dictionary更改为NSMutableDictionary
dict["key"] = "value"
其他回答
在字典中没有附加数据的函数。您只需根据现有字典中的新键分配值。它将自动向字典中添加值。
var param = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)
输出是这样的
["名称":“阿罗哈”,“用户”:“阿罗哈2”,“问题”:“你是我的”吗?”)
您可以使用以下方式添加,并将Dictionary更改为NSMutableDictionary
dict["key"] = "value"
(字符串:任何)
对于使用[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)
}
}
}
要将一个新的键-值对追加到字典中,您只需设置键的值。如。
// 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”)
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]