Best way to populate a dictionary entry only if it does not already exist?

which is the best way to update a dictionary entries one at a time, keeping the old value if the key already exists?

// var modules:[Module.ID: Int]
for graph:Module.Graph in graphs 
{
    // method 1
    self.modules.merge(CollectionOfOne.init(
        (graph.id, self.modules.count)))
    {
        (incumbent, _) in incumbent
    }

    // method 2
    self.modules[graph.id] = self.modules[graph.id] ?? self.modules.count
}

I lean towards your #2 with an additional check to not change the dictionary entries to the same values:

graphs.forEach { graph in
    if modules[graph.id] == nil {
        modules[graph.id] = modules.count
    }
}
2 Likes