This post isn't about the rights and wrongs of using operands to combine or add to dictionaries. I was simply looking through StackOverflow and found a question on the subject, which was linked to a previous one and thought that the response could be expanded upon with a few more cases:
func +=<K, V> (inout left: [K : V], right: [K : V]) { for (k, v) in right { left[k] = v } } func +<K, V> (left: [K : V], right: [K : V]) -> [K : V]{var new = [K : V](); for (k, v) in left { new[k] = v }; for (k, v) in right { new[k] = v }; return new } func -<K, V: Comparable> (left: [K : V], right: [K : V]) -> [K : V]{var new = [K : V](); for (k, v) in left { new[k] = v }; for (k,v) in right { if let n = new[k] where n == v { new.removeValueForKey(k)}}; return new } func -<K, V> (left: [K : V], right: [K]) -> [K : V]{var new = [K : V](); for (k, v) in left { new[k] = v }; for k in right { new.removeValueForKey(k)}; return new } func -=<K, V: Comparable> (inout left: [K : V], right: [K : V]){for (k,v) in right { if let n = left[k] where n == v { left.removeValueForKey(k)}}} func -=<K, V> (inout left: [K : V], right: [K]) {for k in right { left.removeValueForKey(k)}}Implementation can follow this kind of pattern (in a playground):
var aDict = ["1": "a"] let bDict = ["2": "b"] aDict += bDict aDict -= bDict aDict -= ["1"] ["1": "a"] - ["2":"a"] var test = ["1": "a"] + ["2": "b"] + ["1":"c"]The main question in writing these functions was how to handle the "-" and "-=" operands. Do we accept keys and values or just a set of keys, and if the former should a key be deleted if the values don't match? Here I've chosen to write a function for each case. Where an array of keys is supplied, all matching keys have their key/value pair removed, and where a dictionary is supplied key/value pairs are only removed if both match. But the latter type of removal can only occur where values are comparable.
Comments
Post a Comment