Skip to content

Instantly share code, notes, and snippets.

@xavierLowmiller
Last active January 17, 2018 16:15
Show Gist options
  • Save xavierLowmiller/824267a5add8fadd820b973eac11ce7d to your computer and use it in GitHub Desktop.
Save xavierLowmiller/824267a5add8fadd820b973eac11ce7d to your computer and use it in GitHub Desktop.
Operator sugar for dictionary merge methods
extension Dictionary {
/// Merges two dictionaries.
/// When a key is present in both dictionaries, `lhs`'s keys are overwritten
///
/// - Parameters:
/// - lhs: The base dictionary. Its keys may be overwritten by `rhs`'s keys
/// - rhs: The added dictionary. Its keys may overwrite `lhs`'s keys
static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
return lhs.merging(rhs, uniquingKeysWith: { $1 })
}
/// Merges two dictionaries.
/// When a key is present in both dictionaries, `lhs`'s keys are overwritten
///
/// - Parameters:
/// - lhs: The base dictionary. Its keys may be overwritten by `rhs`'s keys
/// - rhs: The added dictionary. Its keys may overwrite `lhs`'s keys
static func += (lhs: inout [Key: Value], rhs: [Key: Value]) {
lhs.merge(rhs, uniquingKeysWith: { $1 })
}
}
//let dict1 = ["key1": 1]
//let dict2 = ["key2": 2]
//
//let d = dict1 + dict2
//
//var c = dict1
//c += dict2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment