Dictionary and SetAlgebra

How come Dictionary and Dictionary.Keys don't conform to SetAlgebra? The constant-time lookups could implement the various method roughly as efficiently as Set.

My use case is that I want to diff two dictionaries to update a view selectively. I want to find out which key/value pairs are new, which ones changes, and which ones go deleted. If Dictionary.Keys conformed to SetAlgebra, I would just do something like:

let newKeys = newDict.keys.subtracting(oldDict.keys)
let commonKeys = newDict.keys.intersecting(oldDict.keys)
let removedKeys = oldDict.keys.subtracting(newDict.keys)

I could do all this by hopping through Set first, but it's one extra step that I suspect shouldn't have to exist.

SetAlgebra.subtracting returns Self. SetAlgebra also requires you be able to create one from scratch from another sequence of elements. These kind of requirements would require the implementation of Dictionary.Keys be something that can stand alone from Dictionary in some way when necessary, unlike the current implementation which is just a projection of the underlying type. It's possible this could all be made to work somehow, but it's far from an obvious conformance for the type.

2 Likes