Adding values ββto a dictionary with quick
I have this dictionary:
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]
and I want to add values, for example to get the result as 30, how can I do that? In other words, how can I only add numbers and not words?
As described in the docs here. You access and modify the dictionary through its methods and properties, or through substring syntax. Read the document.
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]
To access a value in a dictionary, you can use the substring 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 meaning 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
}
Since the answer is accepted and not very good, I will have to abandon 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 of dict.values
and decreasing them
let sum = Array(dict.values).reduce(0, +)
Or you can use a simple Reduce form that doesn't require the initial creation of the array:
let sum = reduce(dict.values, 0, +)
Or a more modern version, since it reduce
is defined on an array
let sum = dict.values.reduce(0, +)
The accepted answer does not use the power of the swift
and the answer that does this is out of date.
Simplest updated solution:
let valuesSum = dict.values.reduce(0, +)
start from zero and sum the values ββof all elements