Swift standard library has some functions to merge 2 dictionaries.
https://developer.apple.com/documentation/swift/dictionary/3127171-merge
https://developer.apple.com/documentation/swift/dictionary/3127175-merging
mutating func merge<S>(_ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows where S : Sequence, S.Element == (Key, Value)
func merging<S>(_ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> [Key : Value] where S : Sequence, S.Element == (Key, Value)
I feel having to specify this combine closure every time I call this function is too verbose. Imagine a code base with a lot dictionary merging, you will see a lot of repeating combine closures that either select current or new value for duplicated keys. Like this:
let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
I know that having a combine closure is useful because it can handle cases where you might not want to choose either current or new values, but to create a completely new value from the two. But I still think it is too verbose for simple use cases that I want to just either pick one of the values.
What I'm proposing is there should be another function dictionary merging/updating function that automatically pick one of the duplicated keys without specifying a combining closure. I think this way is more concise and readable.
I'm throwing some ideas of the function name may look like.
For updating keeping current keys:
let keepingCurrent = dictionary.updateByKeepingCurrent(using: newKeyValues)
let keepingCurrent = dictionary.updateIfNew(using: newKeyValues)
let keepingCurrent = dictionary.addIfNotExist(using: newKeyValues)
For updating replacing current keys:
let replacingCurrent = dictionary.updateByReplacingCurrent(using: newKeyValues)
let replacingCurrent = dictionary.update(using: newKeyValues)
let replacingCurrent = dictionary.addOrReplace(using: newKeyValues)
Another idea is to just make dictionary types support binary operators like +
and +=
. But one may argue that this is too far of an approach and is prone to correctness and safety. Because the detail of how the duplicated keys are resolved is not visible in these operators.
I feel this is such a fundamental feature that might had been discussed before and Swift team might already discarded or not prioritized yet. However, I can't find a reference to such discussions. Even if this idea is discarded, I will be happy to learn the reasons why.
Let me know what you guys think.