Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

swift2 - cannot subscript a value of type 'inout' [String :Double] (aka 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)"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...