stack
stack

Reputation: 287

Adding Values In Dictionary With Swift

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?

Upvotes: 5

Views: 4469

Answers (3)

Abizern
Abizern

Reputation: 150665

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, +)

Upvotes: 12

inteist
inteist

Reputation: 503

The accepted answer doesn't use the power of swift

and the answer that does is outdated.

The simplest updated solution is:

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

start with zero, and sum the values of all the elements

Upvotes: 5

Kalenda
Kalenda

Reputation: 1927

As explained in the documentations here. You access and modify a dictionary through its methods and properties, or by using subscript syntax. Read the doc.

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

To access a value in your dictionary you can use the subscript syntax:

if let cola = dict["cola"] as? Int { // to read the value
    // Do something 
}
dict["cola"] = 30 // to change the value  
dict["pepsi"] = 25 // to add a new entry to your dictionary
dict["fanta"] = nil // to delete the fanta entry. 

to read all the value in your dictionary

var sum = 0
for (drinkName, drinkValue) in dict {
    println("\(drinkName): \(drinkValue)")
    sum += drinkValue
}

or you can

var sum = 0
for drinkValue in dict.values {
   sum += drinkValue
}

Upvotes: 3

Related Questions