问题在于您正在创建新的通用 K、V 值类型。您只需要在方法声明中省略它们即可。顺便说一句,您忘记添加一个方法来总结两个非可选字典:
extension Dictionary {
public static func +=(lhs: inout Dictionary, rhs: Dictionary) {
lhs.merge(rhs)
}
public static func +=(lhs: inout Dictionary, rhs: Dictionary?) {
if let rhs = rhs { lhs.merge(rhs) }
}
public static func +=(lhs: inout Dictionary?, rhs: Dictionary) {
if var lhs = lhs { lhs.merge(rhs) } else { lhs = rhs }
}
public static func +(lhs: Dictionary, rhs: Dictionary) -> Dictionary {
lhs.merging(rhs)
}
public static func +(lhs: Dictionary, rhs: Dictionary?) -> Dictionary {
if let rhs = rhs { return lhs.merging(rhs) }
return lhs
}
public static func +(lhs: Dictionary?, rhs: Dictionary) -> Dictionary {
if let lhs = lhs { return lhs.merging(rhs) }
return rhs
}
@inlinable public mutating func merge(_ other: Dictionary) {
self.merge(other) {$1}
}
@inlinable public func merging(_ other: Dictionary) -> Dictionary {
self.merging(other) {$1}
}
}
let dicSum = ["a" : "A"] + ["b" : "B"]
dicSum // ["b": "B", "a": "A"]
另一种方法是为 Dictionary 泛型 Key 和 Value 类型创建类型别名,并删除您在方法声明 <K,V> 中创建的那些,否则它们将再次成为与 Dictionary declaration 中定义的类型无关的新泛型类型:
extension Dictionary {
public typealias K = Key
public typealias V = Value
public static func +=(lhs: inout [K: V], rhs: [K: V]) {
lhs.merge(rhs)
}
public static func +=(lhs: inout [K: V], rhs: [K: V]?) {
if let rhs = rhs { lhs.merge(rhs) }
}
public static func +=(lhs: inout [K: V]?, rhs: [K: V]) {
if var lhs = lhs { lhs.merge(rhs) } else { lhs = rhs }
}
public static func +(lhs: [K: V], rhs: [K: V]) -> [K: V] {
lhs.merging(rhs)
}
public static func +(lhs: [K: V], rhs: [K: V]?) -> [K: V] {
if let rhs = rhs { return lhs.merging(rhs) }
return lhs
}
public static func +(lhs: [K: V]?, rhs: [K: V]) -> [K: V] {
if let lhs = lhs { return lhs.merging(rhs) }
return rhs
}
@inlinable public mutating func merge(_ other: [K: V]) {
self.merge(other) {$1}
}
@inlinable public func merging(_ other: [K: V]) -> [K: V] {
self.merging(other) {$1}
}
}
这与上面所做的完全相同。
同样Dictionary、Dictionary<Key, Value> 和[Key:Value] 完全一样:
extension Dictionary {
public static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
lhs.merge(rhs)
}
public static func +=(lhs: inout [Key: Value], rhs: [Key: Value]?) {
if let rhs = rhs { lhs.merge(rhs) }
}
public static func +=(lhs: inout [Key: Value]?, rhs: [Key: Value]) {
if var lhs = lhs { lhs.merge(rhs) } else { lhs = rhs }
}
public static func +(lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
lhs.merging(rhs)
}
public static func +(lhs: [Key: Value], rhs: [Key: Value]?) -> [Key: Value] {
if let rhs = rhs { return lhs.merging(rhs) }
return lhs
}
public static func +(lhs: [Key: Value]?, rhs: [Key: Value]) -> [Key: Value] {
if let lhs = lhs { return lhs.merging(rhs) }
return rhs
}
@inlinable public mutating func merge(_ other: [Key: Value]) {
self.merge(other) {$1}
}
@inlinable public func merging(_ other: [Key: Value]) -> [Key: Value] {
self.merging(other) {$1}
}
}
实现它的所有 3 种方法都是等效的。选择你觉得舒服的那个。