Error trying to perform addition using dictionary in swift [duplicate]

流过昼夜 提交于 2019-12-11 04:58:17

问题


teaching myself swift I am trying to understand how dictionaries work. Using playground. I have made a simple dictionary called "menu" that has a list of items with their name as keys and their price as values. Like so:

let menu = ["crisps": 2,
            "oranges": 3,
            "chicken": 8,
            "meat": 12]

Then, I try to add the values of those items like so:

let costOfMeal = menu["crisps"]! + menu["oranges"]! + menu["chicken"]! + menu["meat"]!

This gives me the error: ambiguous reference to member '+'

not sure what's going on. Any input appreciated.

Thanks,

David


回答1:


This is merely the compiler's automatic type casting getting confused by the multiple additions of unwrapped optionals.

You can help it along by adding an actual integer in the formula.

let costOfMeal =  0 + menu["crisps"]! + menu["oranges"]! + menu["meat"]! + menu["chicken"]!

Don't let it bother you as it has nothing to do with what you're trying to learn and your formula was correct (albeit not safe for production).




回答2:


let costOfMeals = Array(menu.values).reduce(0, +)

You are trying to add up every key and value together! You should only add up the values. You know the dictionary is Key and Value, and you should only add up the Value's.



来源:https://stackoverflow.com/questions/42568446/error-trying-to-perform-addition-using-dictionary-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!