用于返回组合字典的字典扩展

我试图以下列方式扩展Swift的词典类:

extension Dictionary { func merge<K, V>(dict: [K:V]) -> Dictionary<K, V> { var combinedDict: [K:V] = [:] for (k, v) in self { combinedDict[k] = v } for (k, v) in dict { combinedDict[k] = v } return combinedDict } } 

第一个for循环给我的错误:“不能下标types'[K:V]'的值types'Key'的索引”,但第二个循环是好的。 我甚至评论了第一个检查,第二个仍然有效。 任何人都知道问题是什么? 谢谢!

字典types已经将KeyValue定义为通用variables,所以不需要KV (并导致问题)。

 extension Dictionary { func merge(dict: [Key : Value]) -> [Key : Value] { var combinedDict = self for (k, v) in dict { combinedDict[k] = v } return combinedDict } } 

字典的通用占位符types称为键和值,您必须保留这些名称; 你不能随便把它们重命名为K和V.

这是我使用的实现:

 extension Dictionary { mutating func addEntriesFromDictionary(d:[Key:Value]) { // generic types for (k,v) in d { self[k] = v } } } 

这个代码如何?

  extension Dictionary { func merge(other: [Key: Value]) -> [Key: Value] { var ret: [Key: Value] = self for (key, value) in other { ret[key] = value } return ret } }