With Swift 4, according to your needs, you may choose one of the following solutions in order to solve your problem.
#1 Using Dictionary subscript(_:default:)
Dictionay has a subscript called subscript(_:default:). subscript(_:default:) has the following declaration:
subscript(key: Dictionary.Key, default defaultValue: @autoclosure () -> Dictionary.Value) -> Dictionary.Value { get set }
Accesses the element with the given key, or the specified default value, if the dictionary doesn’t contain the given key.
The following Playground example shows how to use subscript(_:default:) in order to solve your problem:
struct Item {
let date: String
let amount: Double
}
let data = [
Item(date:"2017.02.15", amount: 25),
Item(date:"2017.02.14", amount: 50),
Item(date:"2017.02.11", amount: 35),
Item(date:"2017.02.15", amount: 15)
]
var dictionary = [String: Double]()
for item in data {
dictionary[item.date, default: 0.0] += item.amount
}
print(dictionary) // ["2017.02.11": 35.0, "2017.02.15": 40.0, "2017.02.14": 50.0]
#2 Using Dictionary init(_:uniquingKeysWith:) initializer
Dictionay has a init(_:uniquingKeysWith:) initializer. init(_:uniquingKeysWith:) has the following declaration:
init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows where S : Sequence, S.Element == (Key, Value)
Creates a new dictionary from the key-value pairs in the given sequence, using a combining closure to determine the value for any duplicate keys.
The following Playground example shows how to use init(_:uniquingKeysWith:) in order to solve your problem:
struct Item {
let date: String
let amount: Double
}
let data = [
Item(date:"2017.02.15", amount: 25),
Item(date:"2017.02.14", amount: 50),
Item(date:"2017.02.11", amount: 35),
Item(date:"2017.02.15", amount: 15)
]
let tupleArray = data.map({ ($0.date, $0.amount) })
let dictonary = Dictionary(tupleArray, uniquingKeysWith: { (current, new) in
current + new
})
//let dictonary = Dictionary(tupleArray, uniquingKeysWith: +) // also works
print(dictonary) // prints ["2017.02.11": 35.0, "2017.02.15": 40.0, "2017.02.14": 50.0]
Stringrepresentation of yourDateto be the key (not theDateitself). Also, ifDateis not a typealias forString,theItemdefault initializer calls when instantiating thedataarray wont compile.