cannot subscript a value of type 'inout' [String :Double] (aka inout Dictionary<String, Double>)

点点圈 提交于 2019-12-17 21:36:04

问题


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

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


回答1:


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)


来源:https://stackoverflow.com/questions/39913093/cannot-subscript-a-value-of-type-inout-string-double-aka-inout-dictionary

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