Pangu
Pangu

Reputation: 3819

iOS Swift: How to calculate the sum of each value in a key-pair dictionary and store it in a separate dictionary?

Currently I have a dictionary array that is defined like so:

var dateDouble_ARRAY = [Date : [Double] ]()

dateDouble_ARRAY = [2017-08-06 07:00:00 +0000: [11.880000000000001, 3.0], 
    2013-08-08 07:00:00 +0000: [5.0], 
    2016-08-01 07:00:00 +0000: [6.0], 
    2017-08-09 07:00:00 +0000: [6.0], 
    2013-08-02 07:00:00 +0000: [5.0], 
    2012-08-03 07:00:00 +0000: [6.5499999999999998], 
    2015-08-10 07:00:00 +0000: [2.0] ]

What I would like to do is get the year of all the dates and store it in a [String: Double] key-value dictionary where the value paired up with the year key is the sum of all the values for that specific year.

For example, in the above code, the following would be the desired output:

var yearDouble_ARRAY = [ "2012": 6.5499999999999998, 
                         "2013": 10.0, 
                         "2015": 2.0, 
                         "2016": 6.0, 
                         "2017: 20.880000000000001]

NOTE: For "2017", 20.880000000000001 is obtained from [ (11.880000000000001 + 3.0) + 6.0].

How can I achieve the desired effect?

Thanks!

What I have tried so far

var stringDates = [String: Int]()

for (index, date) in dateDouble_ARRAY.enumerated()
{
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy"

    let yearOnly = formatter.string(from: date.key)

    stringDates[yearOnly] = index
}

let yearOnly_ARRAY = stringDates.keys.sorted()

However, I was only able to store the non-repeated years, I'm not sure how to sum the values associated with the year.

Upvotes: 0

Views: 825

Answers (1)

nathan
nathan

Reputation: 9395

Your code was only missing the sum of the current Doubles:

let datesDoubles = [
    Date(): [11.880000000000001, 3.0],
    Date(timeIntervalSinceNow: 3600 * 24 * 60 * -1 ): [6.0],
    Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1): [5.0],
    Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 2): [6.0],
    Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 4): [5.0],
    Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 5): [6.5499999999999998],
    Date(timeIntervalSinceNow: 3600 * 24 * 365 * -1 * 6): [2.0]
]

var stringDates = [String : Double]()
let formatter: DateFormatter = {
    $0.dateFormat = "yyyy"
    return $0
}(DateFormatter())

for dateDouble in datesDoubles {
    let yearOnly = formatter.string(from: dateDouble.key)

    if let valueForDate = stringDates[yearOnly] {
        stringDates[yearOnly] = valueForDate + dateDouble.value.reduce(0,+)
    } else {
        stringDates[yearOnly] = dateDouble.value.reduce(0,+)
    }
}

print(stringDates)

Upvotes: 2

Related Questions