Fattaneh Talebi
Fattaneh Talebi

Reputation: 767

How to append an element to dictionary when the key exist or not exist in swift

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

Answers (1)

Leo Dabus
Leo Dabus

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

Related Questions