Dictionary error: Ambiguous reference to member '+'

时间:2016-12-09 13:08:45

标签: ios swift swift3

I have the following code in a swift 3 method:

let dict = ["A": 1, "B": 2, "C": 3]
let sum = dict["A"]! + dict["B"]! + dict["C"]!

The code does not compile because of the Ambiguous reference to member '+' error. But if I try to add only two elements it compile and works as expected.

let dict = ["A": 1, "B": 2, "C": 3]
let sum = dict["A"]! + dict["B"]!

Works normally.

Am I missing something from how the language should work?

4 个答案:

答案 0 :(得分:1)

另一种解决方法:

let dict = ["A": 1, "B": 2, "C": 3]
let sum = 0 + dict["A"]! + dict["B"]! + dict["C"]!

答案 1 :(得分:0)

您可以将dict["A"]Int一起打包来解决错误。

这会将键“A”的值转换为Int,允许我们正确添加。

let dict = ["A": 1, "B": 2, "C": 3]
let sum = Int(dict["A"]!) + Int(dict["B"]!) + Int(dict["C"]!)

答案 2 :(得分:0)

此代码已成功编译:

struct

我想,这个问题与复杂的表达有关。您可以阅读有关构建时间优化的更多信息in this article

答案 3 :(得分:0)

正如其他人评论的那样,这似乎是一个错误。但是,似乎你不太可能遇到这种情况,因为强行打开这样的字典元素是非常不安全的。这很好用:

let dict = ["A": 1, "B": 2, "C": 3]

if
  let a = dict["A"],
  let b = dict["B"],
  let c = dict["C"]
{
  let sum = a + b + c
}