Friday Q & A 2017-10-06: Type-Safe User Standards
It's fun to imagine traditional techniques with a swift twist. I have implemented a kind of safe team on top of the venerable
NSUserDefaults and I will discuss my small library today. Credit / blame for this idea goes to local reader José Vazquez, although he accidentally inspired it while talking about something else.
UserDefaultsin Swift is a typical dynamic written strict-oriented Objective-C API. It stores string keys and property list values. This is perfectly fine, but I would do better. I came up with this wish list:
- Keys must be declared, not written ad hoc at the place of use. You can do this with
UserDefaultsby declaring string constants, but it's easy to get lazy and not do it.
- It should not be repeated in the usual case. A key string should be automatically made to match its identifier in the code.
- No casting should be required. Keys should have a value pair attached to them and the conversion is handled internally.
- It should interact evenly with the values read and written directly through
- Selection Type Types To Be Supported Through
- Default values should be specified as part of the key instead of being registered separately.
- The value should be made available as a property so the goal can be to mutate methods and operators.
As usual, the code is available on GitHub if you want to play with it or see it all in one place:
Example Use [1
To declare a key, type a
struct in accordance with the protocol
TSUD . Inside, implementing a single
static property called
defaultValue containing the value to be returned if
UserDefaults does not contain a value:
struct la  DefaultValue = 12.0 }
To read or write the value, use
[Size: [Size: 19659021] : fontSize . value )
fontSize . value = 14.0
value is only a property you can make disruptive and unnatural things like
+ = to it.
If you want to discover the lack of a value and handle it specially than get a default value, declare