Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Values In Dictionary With Swift

Tags:

swift

ios8

I have this Dictionary:

var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]

and I want to add the values for example to have the result as 30 , how can I do that? In other words, how can I only add the numbers, not the words?

like image 830
stack Avatar asked Dec 02 '22 15:12

stack


1 Answers

Since an answer has been accepted and it isn't a very good one, I'm going to have to give up on the socratic method and show a more thematic way of answering this question.

Given your dictionary:

var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]

You get the sum by creating an array out of the dict.values and reducing them

let sum = Array(dict.values).reduce(0, +)

Or you could use the bare form of reduce which doesn't require the array to be created initially:

let sum = reduce(dict.values, 0, +)

Or the more modern version, since reduce is defined on an Array

let sum = dict.values.reduce(0, +)
like image 173
Abizern Avatar answered Dec 18 '22 00:12

Abizern