Created
October 12, 2021 05:59
-
-
Save ppeelen/b128d617cc220ac0d45a6dc91918769d to your computer and use it in GitHub Desktop.
Dictionary comparison
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
import Foundation | |
let dictOne: [String: String] = [ | |
"key1": "value one", | |
"key2": "value two", | |
"key3": "value three", | |
"key4": "value four" | |
] | |
let dictTwo: [String: String] = [ | |
"key1": "value one", | |
"key3": "value 3", | |
"key4": "value four", | |
"key5": "value five" | |
] | |
let addedKeys = Array(Set(dictTwo.keys).subtracting(Set(dictOne.keys))) | |
let removedKeys = Array(Set(dictOne.keys).subtracting(Set(dictTwo.keys))) | |
let remainingKey = Array(Set(dictTwo.keys).subtracting(Set(removedKeys)).subtracting(Set(addedKeys))) | |
let changedKeys = remainingKey.compactMap { (dictOne[$0] != dictTwo[$0]) ? $0 : nil } | |
debugPrint("Added keys: \(addedKeys)") // "Added keys: [\"key5\"]" | |
debugPrint("Removed keys: \(removedKeys)") // "Removed keys: [\"key2\"]" | |
debugPrint("Remaining keys: \(remainingKey)") // "Remaining keys: [\"key1\", \"key4\", \"key3\"]" | |
debugPrint("Changed keys: \(changedKeys)") // "Changed keys: [\"key3\"]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment