A Case For OOP?
Python's standard library includes a very handy
defaultdict. It behaves
almost exactly like the standard dictionary except it'll supply a pre-defined
value for any non-existence keys. It is, unsurpringly, a subclass of
I find my self missing this handy container in Swift. Especially when I use
Dictionary to accumulate/coalesce values under distinct keys. So I
wrote my own:
There are a few noticable things about this implementation:
- It does not conform to the
DictionaryLiteralConvertibleprotocol, for no good reasons, really. The initializer in this protocol takes a varadic argument. There's no conevient way to forward this array to a normal dictionary's initializer (incidentally, this is a Swift feature I really want). Plus, I don't need
DefaultDictionaryto be a literal convertible.
- Most of the code, including the imaginary
initmentioned in previous point, simply reuses stuff from
Dictionary: asscociated type, indexes, generator, subscript, etc.
In comparison, Python implements
defaultdict in a more intuitive way -- via
But do we want inheritance for
enums in Swift? What does that
even mean? Is it simply a case that will go away when protocols become more