Created
August 20, 2015 20:53
-
-
Save zats/f9cde500c14230447a15 to your computer and use it in GitHub Desktop.
Abandoned dictionary diffing in swift
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 | |
extension Dictionary { | |
static func keyDifference<Value: Equatable>(dictionary1 dic1: Dictionary<Key, Value>, dictionary2 dic2: Dictionary<Key, Value>, inout inserted: Set<Key>, inout deleted: Set<Key>, inout updated:Set<Key>, inout unchanged: Set<Key>) { | |
let keys1 = Set(dic1.keys.array) | |
let keys2 = Set(dic2.keys.array) | |
let allKeys = keys1.union(keys2) | |
inserted = [] | |
deleted = [] | |
updated = [] | |
unchanged = [] | |
for key in allKeys { | |
switch (dic1[key], dic2[key]) { | |
case (.None, .Some(let _)): | |
inserted.insert(key) | |
case (.Some(let _), .None): | |
deleted.insert(key) | |
case (.Some(let v1), .Some(let v2)): | |
if v1 == v2 { | |
unchanged.insert(key) | |
} else { | |
updated.insert(key) | |
} | |
default: | |
assertionFailure("Key \"\(key)\" must exist in either one or another dictionary") | |
break | |
} | |
} | |
} | |
} | |
extension NSDictionary { | |
static func wml_keyDifferenceBetweenDictionary(dic1: NSDictionary, andDictionary dic2: NSDictionary, inserted: UnsafeMutablePointer<NSSet>, deleted: UnsafeMutablePointer<NSSet>, updated: UnsafeMutablePointer<NSSet>, unchanged: UnsafeMutablePointer<NSSet>) { | |
if let dic1 = dic1 as? [String: NSObject], | |
dic2 = dic2 as? [String: NSObject] { | |
var outInserted: Set<String> = [], outDeleted: Set<String> = [], outUpdated: Set<String> = [], outUnchanged: Set<String> = [] | |
[String: NSObject].keyDifference(dictionary1: dic1, dictionary2: dic2, inserted: &outInserted, deleted: &outDeleted, updated: &outUpdated, unchanged: &outUnchanged) | |
inserted.initialize(outInserted) | |
deleted.initialize(outDeleted) | |
updated.initialize(outUpdated) | |
unchanged.initialize(outUnchanged) | |
} else { | |
assertionFailure("Can't process dictionaries: unexpected types") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment