Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created September 8, 2023 08:44
Show Gist options
  • Save laevandus/246dccb1d98c1799135077448d69e31f to your computer and use it in GitHub Desktop.
Save laevandus/246dccb1d98c1799135077448d69e31f to your computer and use it in GitHub Desktop.
let first = ["a": 1, "b": 2]
let second = ["a": 9, "c": 3]
// value in `first` wins if the same key in both
let merged1 = first.merging(second, uniquingKeysWith: { current, _ in current })
// value in `second` wins if the same key in both
let merged2 = first.merging(second, uniquingKeysWith: { _, new in new })
extension Dictionary {
func mergingUniqueKeys(from other: [Key: Value]) -> [Key: Value] {
merging(other, uniquingKeysWith: { current, _ in current })
}
}
// value in `first` wins if the same key in both
let merged3 = first.mergingUniqueKeys(from: second)
// -> ["b": 2, "a": 1, "c": 3]
// value in `second` wins if the same key in both
let merged4 = second.mergingUniqueKeys(from: first)
// -> ["b": 2, "c": 3, "a": 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment