引用类型 "_" 的错误:"Cannot assign value of type '[Value]' to type '_?'"



我正在尝试合并两个Dictionary对象。当它们都有keyvalue时,我希望第二个Dictionay的值覆盖第一个,但有几个例外:

  • 当两个值都Dictionary对象时,我希望它们被合并,以递归的方式使用相同的方法。
  • 当两个值都Array对象时,我希望将它们连接起来。

我的代码如下:

extension Dictionary where Key:Hashable, Value:AnyObject {
func merge(with second: [Key : Value]) -> [Key : Value] {
var resultDictionary = self
for (key, value) in second {
switch value {
case let newDict as [Key : Value]:
if let oldDict = resultDictionary[key] as? [Key : Value] {
resultDictionary[key] = oldDict.merge(with: newDict) // 1
} else {
resultDictionary[key] = newDict // 2
}
case let newArray as [Value]:
if let oldArray = resultDictionary[key] as? [Value] {
resultDictionary[key] = oldArray + newArray // 3
} else {
resultDictionary[key] = newArray // 4
}
default:
resultDictionary[key] = value
}
}
return resultDictionary
}
}

我在评论行上:

  1. 无法将类型为"[键:值]"的值转换为预期的参数类型"[_ : _]">
  2. 无法将类型"[键:值]"的值分配给类型"_?"。
  3. 无法将类型"[值]"的值分配给类型"_?">
  4. 无法将类型"[值]"的值分配给类型"_?">

我认为所有这些错误都是相同的,如果不是密切相关的话。似乎下划线在这里用作类型,但我不是在这种情况下的意思。我认为下划线仅用于表示未使用的变量。

您可以通过将表达式一分为二来意识到您的错误:

let newValue: [Key: Value] = oldDict.merge(with: newDict)
resultDictionary[key] = newValue // 1

请注意,现在您正在将[Key: Value]字典分配给需要类型Value的内容。

你需要一个演员

resultDictionary[key] = newValue as? Value // 1

从类型的角度来看,这一切都很奇怪。您不应该尝试将字典转换为某些提供的类型。

为什么不只将函数添加到AnyObject作为值的字典中?

extension Dictionary where Key:Hashable, Value == AnyObject

然后

resultDictionary[key] = newValue as AnyObject

该演员表现在是编译时演员表,很好,很安全。

最新更新