I am learning a little bit about Swift and am following along with a Udemy course. The course is taught in swift 2 and I am using swift 3 so I am hoping to understand the difference in outputs and I cannot find any answer online thus far.
I have a dictionary item which contains 3 things.
var menu = ["entre" : 5.55, "main-meal": 20.50, "desert": 5.50]
The idea is to add the 3 values together using the instructors output (which works fine in swift 2):
var totalCost = menu["entre"]! + menu["desert"]! + menu["main-meal"]!
Within the course this works just fine but for me it throws an error that reads "Cannot subscript a value of type 'inout [String : Double]' (aka 'inout Dictionary')"
What I find very odd is that if I only use 2 values, all is fine, the problem is when the third is added. I can get around the issue by adding + 0.0 to the end as below:
var totalCost = menu["entre"]! + menu["desert"]! + menu["main-meal"]! + 0.0
What I am hoping to understand is what is the difference between the two versions and ideally what I am doing wrong in adding the 3 together without my workaround.
Thanks in advance.
let (entreCost, desertCost, mainCost) = (menu["entre"]!, menu["desert"]!, menu["main-meal"]!)
let totalCost = entreCost + desertCost + mainCost
let keysToSum = ["entre", "desert", "main-meal"]
keysToSum.map{ menu[$0]!}.reduce(0, +)
menu.values.reduce(0, +)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With