Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Created October 12, 2021 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppeelen/b128d617cc220ac0d45a6dc91918769d to your computer and use it in GitHub Desktop.
Save ppeelen/b128d617cc220ac0d45a6dc91918769d to your computer and use it in GitHub Desktop.
Dictionary comparison
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