Created
January 23, 2019 12:36
-
-
Save cemolcay/175758e21e38c94b096ce1217782ed64 to your computer and use it in GitHub Desktop.
Adds + and += operators to dictionary
This file contains hidden or 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
/// 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