Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created April 10, 2022 00:04
Show Gist options
  • Save laevandus/f35dd0b3f150efff46b1a79eea10c4a7 to your computer and use it in GitHub Desktop.
Save laevandus/f35dd0b3f150efff46b1a79eea10c4a7 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