The input
First of all let's assign good names to the input constants
let monthStrings = ["February 2016", "March 2016", "June 2017", "October 2017", "January 2018", "April 2019"]
let paymentStrings = ["1000", "2000", "3000", "1000", "2000", "3000"]
What can go wrong
We are working with strings as input, so many things could go wrong during the parsing of a Date or of an Int. For clarity lets define the following enum
enum Error: ErrorType {
case InputParamsHaveDifferentSizes(Int, Int)
case FirstParamHasInvalidDate
case SecondParamHasInvalidInt
}
The function
func groupData(monthStrings: [String], paymentsStrings:[String]) throws -> [Int:Int] {
// make sure both arrays have the same size
guard monthStrings.count == paymentStrings.count
else { throw Error.InputParamsHaveDifferentSizes(monthStrings.count, paymentStrings.count) }
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM yyyy"
// creates dates: an array of NSDate representing monthStrings
// if dates has a different size of monthsString then throws and error
guard
case let dates = (monthStrings.flatMap { formatter.dateFromString($0) })
where dates.count == monthStrings.count
else { throw Error.FirstParamHasInvalidDate }
// creates payments: an array of Int representing paymentsStrings
// if payments has a different size of paymentsStrings then throws and error
guard
case let payments = (paymentStrings.flatMap { Int($0) })
where payments.count == paymentStrings.count
else { throw Error.SecondParamHasInvalidInt }
// put togheter dates and payments and group the results by year
return zip(dates, payments).reduce([Int:Int]()) { (var result, elm) -> [Int:Int] in
let year = NSCalendar.currentCalendar().components([NSCalendarUnit.Year], fromDate: elm.0).year
result[year] = elm.1 + (result[year] ?? 0)
return result
}
}
Usage
let res = try groupData(monthStrings, paymentsStrings: paymentStrings)
print(res) // [2018: 2000, 2017: 4000, 2016: 3000, 2019: 3000]
Update
In the comment below you say you need to access the keys by index and you need them sorted so
let sortedKeys = res.keys.sort()
func value(index:Int) -> String? {
let key = sortedKeys[index]
let value = res[key]
return value
}
year? Is it[NSDate]or just[String]? Either way, I would use a dictionary instead like:[Int: Double].