Created
February 6, 2021 18:33
-
-
Save leopic/d874401c235bf413807fa77e1105b398 to your computer and use it in GitHub Desktop.
Recursively merging dictionaries
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
static func mergeBlocks(base: [String: Any], replacement: [String: Any]) -> [String: Any] { | |
var result = base.merging(replacement) { $1 } | |
for key in base.keys { | |
guard let val = base[key] else { continue } | |
guard let json = val as? [String: Any], | |
let replacement = replacement[key] as? [String: Any] else { | |
continue | |
} | |
result[key] = mergeBlocks(base: json, replacement: replacement) | |
} | |
return result | |
} | |
// Specs | |
describe("mergeBlocks(base:replacement:") { | |
it("correctly merges recursive structures") { | |
let base: [String: Any] = [ | |
"key": "value", | |
"nested": [ | |
"innerKey": "innerValue", | |
"second": [ | |
"a": "b", | |
"c": "c", | |
"fourth": [ | |
"2": false | |
] | |
] | |
] | |
] | |
let replacement: [String: Any] = [ | |
"otherKey": "otherValue", | |
"nested": [ | |
"otherInnerKey": "otherInnerValue", | |
"innerKey": "newInnerValue", | |
"second": [ | |
"c": "d", | |
"third": [ | |
"1": true | |
] | |
] | |
] | |
] | |
let result = Dictionary<String, Any>.mergeBlocks(base: base, replacement: replacement) | |
let expectation: [String: Any] = [ | |
"otherKey": "otherValue", | |
"key": "value", | |
"nested": [ | |
"innerKey": "newInnerValue", | |
"otherInnerKey": "otherInnerValue", | |
"second": [ | |
"a": "b", | |
"c": "d", | |
"third": ["1": true], | |
"fourth": ["2": false], | |
], | |
] | |
] | |
expect(result.keys).to(equal(expectation.keys)) | |
let nestedResult = result["nested"] as! [String: Any] | |
let nestedExpectation = expectation["nested"] as! [String: Any] | |
expect(nestedResult.keys).to(equal(nestedExpectation.keys)) | |
expect(nestedResult["innerKey"] as? String).to(equal(nestedExpectation["innerKey"] as? String)) | |
expect(nestedResult["otherInnerKey"] as? String).to(equal(nestedExpectation["otherInnerKey"] as? String)) | |
let deeplyNestedResult = nestedResult["second"] as! [String: Any] | |
let deeplyNestedExpectation = nestedExpectation["second"] as! [String: Any] | |
expect(deeplyNestedResult.keys).to(equal(deeplyNestedExpectation.keys)) | |
expect(deeplyNestedResult["a"] as? String).to(equal(deeplyNestedExpectation["a"] as? String)) | |
expect(deeplyNestedResult["c"] as? String).to(equal(deeplyNestedExpectation["c"] as? String)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment