Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created January 23, 2019 12:36
Show Gist options
  • Save cemolcay/175758e21e38c94b096ce1217782ed64 to your computer and use it in GitHub Desktop.
Save cemolcay/175758e21e38c94b096ce1217782ed64 to your computer and use it in GitHub Desktop.
Adds + and += operators to dictionary
/// Merges right hand side dictionary into left hand side dictionary. Works on nested dictionaries as well.
///
/// - Parameters:
/// - lhs: Dictionary you want to merge someting.
/// - rhs: Merging dictionary.
/// - Returns: Returns merged dictionary.
internal func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach {
if let dict = $1 as? [Key: Value] {
if let exist = result[$0] as? [Key: Value] {
result[$0] = exist + dict as? Value
} else {
result[$0] = dict as? Value
}
} else {
result[$0] = $1
}
}
return result
}
/// Appends the right hand side dictionary. Works on nested dictionaries as well
///
/// - Parameters:
/// - lhs: Dictionary you want to merge someting.
/// - rhs: Merging dictionary.
internal func +=<Key, Value> (lhs: inout [Key: Value], rhs: [Key: Value]) {
// swiftlint:disable:next shorthand_operator
lhs = lhs + rhs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment