Created
April 10, 2022 00:04
-
-
Save laevandus/f35dd0b3f150efff46b1a79eea10c4a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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