Reputation: 767
I want to append an element to dictionary. And I want to make it if the key not exist.
My solution is this:
if let _ = eventsBySection[key] {
eventsBySection[key]?.append(event)
} else {
eventsBySection[key] = [event]
}
Is it possible to write this code better? or in one line?
Upvotes: 2
Views: 761
Reputation: 236420
You can use nil coalescing operator ??
and provide an empty array in case of nil:
eventsBySection[key] = (eventsBySection[key] ?? []) + [event]
edit/update:
Swift 4 or later You can use Dictionary Key-based subscript with default value
eventsBySection[key, default: []].append(event)
Upvotes: 4