不能下标'inout'类型的值[String:Double](又名inout Dictionary< String,Double>) [英] cannot subscript a value of type 'inout' [String :Double] (aka inout Dictionary<String, Double>)

查看:131
本文介绍了不能下标'inout'类型的值[String:Double](又名inout Dictionary< String,Double>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试在字典中添加三个菜单,那么当我尝试强制打开菜单中的第三个项目时,我不会让我发生错误。但是如果我强制解开其中两个,我可以得到他们的两个总和

How can if i try to add three menus in the dictionary i wont let me and throws an error when i try to force unwrap the 3rd item in the menu. However if i force unwrap two of them, i can get them sum of two

var menu = ["fish": 10.99, "chips": 5.99, "kebab": 6.99]
var totalCost = menu["fish"]! + menu["chips"]! + menu["kebab"]!
print("The total cost of the three items is \(totalCost)")

但是当我以这种方式尝试使用它的时候

But when i tried it this way it worked

var menu = ["fish": 10.99, "chips": 5.99, "kebab": 6.99]
var totalCost = menu["fish"]! + menu["chips"]! 
var thisCost = totalCost + menu["kebab"]!
print("The total cost of the three items is \(thisCost)"

我正在使用swift 3.是否可以在swift 3中不再支持?

I am using swift 3. Could it be that can no longer be supported in swift 3?

推荐答案

你可以一直遍历,添加到总计,更简单的一行长的添加。

You can alway iterate through and add to total, much simpler that a line of long addition.

var totalCost: Double = 0
for each in menu {
    totalCost += each.value
}
print(totalCost)

这篇关于不能下标'inout'类型的值[String:Double](又名inout Dictionary< String,Double>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆