尝试使用字典快速执行加法时出错

尝试使用字典快速执行加法时出错

本文介绍了尝试使用字典快速执行加法时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速上手我正在尝试了解字典的工作方式.使用游乐场.我制作了一个简单的字典,叫做菜单",其中列出了一个项目列表,它们的名称是键,价格是值.像这样:

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.

谢谢

大卫

推荐答案

这仅仅是编译器的自动类型转换,它会因大量添加未包装的可选内容而感到困惑.

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).

这篇关于尝试使用字典快速执行加法时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:48