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?
答案 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)
答案 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
}