我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
我有一个简单的字典,它的定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
现在我想在这个字典中添加一个元素:3:"efg"
我如何能追加3:“efg”到这个现有的字典?
当前回答
我添加了字典扩展
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) }
其他回答
如果你的字典是Int到String,你可以简单地做:
dict[3] = "efg"
如果你的意思是向字典的值中添加元素,一个可能的解决方案是:
var dict = Dictionary<String, Array<Int>>()
dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
你在使用NSDictionary。除非你出于某种原因明确需要它是那种类型,否则我建议使用Swift字典。
你可以将一个Swift字典传递给任何需要NSDictionary的函数,而不需要任何额外的工作,因为dictionary <>和NSDictionary无缝地桥接在一起。原生Swift方式的优点是字典使用泛型类型,所以如果你用Int作为键,String作为值来定义它,你就不会错误地使用不同类型的键和值。(编译器会替你检查类型。)
根据我在你的代码中看到的,你的字典使用Int作为键和字符串作为值。要创建一个实例并在稍后添加一个项,您可以使用以下代码:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
如果你以后需要将它赋值给NSDictionary类型的变量,只需要进行显式强制转换:
let nsDict = dict as! NSDictionary
并且,如前所述,如果你想将它传递给一个期望NSDictionary的函数,就按原样传递它,不需要任何强制转换或转换。
字典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的高阶函数之一来将数据追加到字典中。“减少”。遵循以下代码片段:
newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
@Dharmesh在你的情况下,
newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
请让我知道,如果你发现任何问题在使用上述语法。