Gui*_*ume 2 dictionary operator-overloading swift
我想使用下面的方法连接两个带有+ =运算符重载的字典.
static func += <Key, Value> ( left: inout [Key : Value], right: [Key : Value]) {
for (key, value) in right {
left.updateValue(value, forKey: key)
}
}
Run Code Online (Sandbox Code Playgroud)
要么
static func +=<Key, Value>( left: inout Dictionary<Key ,Value>, right: Dictionary<Key, Value>) {
for (key, value) in right {
left.updateValue(value, forKey: key)
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个实现:
var properties = ["Key": "Value"]
var newProperties = ["NewKey": "NewValue"]
properties += newProperties
Run Code Online (Sandbox Code Playgroud)
我从xCode得到以下错误,
无法将'[String:Any]'类型的值转换为预期的参数类型'inout [_:]'(又名'inout'Dictionary <,_>)
它不起作用,任何人都可以帮助我,或者如果不可能,请解释我为什么?
dfr*_*fri 11
由于Swift 4即将推出,我将添加一个答案(解决,特别是问题或标题),包括其发布时可用的其他方法.
进化提案
在Swift 4中实现,并允许您使用诸如变异merge(_:uniquingKeysWith:)(或非变异merging(_:uniquingKeysWith:))之类的方法来组合两个词典,这也允许您指定如何解决键冲突.
例如,+=使用merge(_:uniquingKeysWith:)右侧边框字典中的关联值覆盖现有键值(碰撞时)来实现您的函数:
extension Dictionary {
static func += (lhs: inout Dictionary, rhs: Dictionary) {
lhs.merge(rhs) { (_, new) in new }
}
}
/* example usage */
var dictA = ["one": 1,
"two": 2,
"three": 3]
let dictB = ["three": 42,
"four": 4]
dictA += dictB
print(dictA)
// ["one": 1, "two": 2, "three": 42, "four": 4]
// (any order is coincidental)
Run Code Online (Sandbox Code Playgroud)
假设您要在Dictionary扩展中定义此重载,请不要引入Key和Value通用占位符;使用已经定义的通用占位符Dictionary(因为您自己介绍的占位符与它们完全无关):
extension Dictionary {
static func += (left: inout [Key: Value], right: [Key: Value]) {
for (key, value) in right {
left[key] = value
}
}
}
var properties = ["Key": "Value"]
let newProperties = ["NewKey": "NewValue"]
properties += newProperties
print(properties) // ["NewKey": "NewValue", "Key": "Value"]
Run Code Online (Sandbox Code Playgroud)
您还可以让Swift通过仅采用Dictionary操作数来推断这一点:
extension Dictionary {
static func += (left: inout Dictionary, right: Dictionary) {
for (key, value) in right {
left[key] = value
}
}
}
Run Code Online (Sandbox Code Playgroud)