Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding doubles contained within a dictionary swift 3

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.

like image 486
James Coate Avatar asked Nov 04 '16 03:11

James Coate


1 Answers

Workarounds

For a few keys

let (entreCost, desertCost, mainCost) = (menu["entre"]!, menu["desert"]!, menu["main-meal"]!)

let totalCost = entreCost + desertCost + mainCost

For a lot of keys

let keysToSum = ["entre", "desert", "main-meal"]
keysToSum.map{ menu[$0]!}.reduce(0, +)

For all keys

menu.values.reduce(0, +)
like image 102
Alexander Avatar answered Sep 19 '22 06:09

Alexander