Adding values ββto a dictionary with quick
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
}
source to share
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, +)
source to share