【问题标题】:How to concatenate two dictionaries with a += operator overload如何使用 += 运算符重载连接两个字典
【发布时间】:2017-07-19 18:37:40
【问题描述】:

我想使用下面的方法将两个字典与 += 运算符重载连接起来。

static func += <Key, Value> ( left: inout [Key : Value], right: [Key : Value]) {
    for (key, value) in right {
        left.updateValue(value, forKey: key)
    }
}

static func +=<Key, Value>( left: inout Dictionary<Key ,Value>, right: Dictionary<Key, Value>) {
    for (key, value) in right {
        left.updateValue(value, forKey: key)
    }
}

有了这个实现:

var properties = ["Key": "Value"]
var newProperties = ["NewKey": "NewValue"]
properties += newProperties

我从 xCode 得到以下错误,

无法将“[String: Any]”类型的值转换为预期的参数类型 'inout [_ : ]' (又名'inout'字典, _>)

它不起作用,任何人都可以帮助我,或者如果不可能,解释我为什么?

【问题讨论】:

  • 请注意,您的代码如上所述编译没有问题。使用minimal reproducible example 创建一个新项目总是一个好主意,以避免不清楚的问题陈述。
  • @MartinR 从技术上讲,它不会在函数被声明为static 的情况下在顶层编译,但是是的 - OP,请始终提供 MCVE。通常我会推迟回答没有 MCVE 的问题,但我认为在这种情况下扩展假设并没有太大的飞跃(Martin 的时机也是令人毛骨悚然的 :))。
  • @Hamish:你说得对,我忘了我已经删除了“静态”。

标签: swift dictionary operator-overloading


【解决方案1】:

Swift 4 选择

由于 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)

【讨论】:

    【解决方案2】:

    假设您在 Dictionary 扩展中定义此重载,请不要引入 KeyValue 通用占位符;使用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"]
    

    你也可以通过 let Swift infer this 来使用 Dictionary 操作数:

    extension Dictionary {
    
        static func += (left: inout Dictionary, right: Dictionary) {
            for (key, value) in right {
                left[key] = value
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 2014-11-09
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多