Inspired by it and by collections I wanted to make an similar interface for UserDefaults that could leverage Generics like this:
It may not have the mnemonics of the aforementioned article but it sure does not obfuscate the use of UserDefaults. Indeed it declared the use of it in a manner that is not obtrusive to legibility.
There came the interest to dabble a little with these implementations to see what features would fit a nice way to wrap UserDefaults. It’s when I stumbled on Custom Collections.
Custom Collections are a very flexible way to create interfaces between a custom data structure and the language syntax features. It contains optional methods for subscripting, concatenating, mapping and so forth. I don’t have much understanding of the
Collection protocols but it’s my understanding that
Dictionary are, indeed, structs with associated types that conform, in their own manner, to the mentioned protocols.
So and idea of this came to form:
It may not be the best implementation but it fits the bill really nicely. Still it does not have the power and flexibility of
Optional, specially because the overloading of the
Assign operator is not allowed by Swift — for important reason.
I intend to try using this implementation on the cases that come across. It’s a pretty weak implementation since it needs explicit protocol conformance to work.
A more powerful version of the
Defaultable protocol it would need to be as expressive as
Codable in the sense that it has to offer means for decoding and encoding data structures, sequences and so forth. Maybe it would be a nice idea to try to combine those two.
In another note, since
UserDefaults is also a Property List abstraction, declaring a
Collection with the methods and behaviour of
Dictionary is not only feasible but interesting interface implementation.
What was written above goes to show the symbolic power of Swift and it’s limitations. It’s a language that has the fundamentals that help the curious mind in trying different ways of solving problems. And, in my opinion, code is about being simple and expressive.