[Draft] UserDefaults Wrapper

(Oliver Schäfer) #1

Hi there,

I've recently developed a wrapper around UserDefaults (formerly known as NSUserDefaults), which adds type safety and omits the need for stringified API calls. I’m not sure if this development fits in here, but anyway I’m going to give it a try:

Since I use UserDefaults for storing preference settings most of the time, I simply called the wrapper class Setting. A typical declaration would look like:

var favoriteLanguage = Setting<String>(key: "favoriteLanguage", defaultValue: "ObjectiveC“)

you can change a setting by simply calling:

favoriteLanguage.value = "Swift“

The Setting type is generic and will accept any class or struct, which conforms to the


protocol (which I also created). This allows enums (which have a UserDefaultConvertible RawValue) to be stored into user defaults like this:

enum Languages: Int, UserDefaultConvertible {
    case Swift = 0
    case ObjectiveC
    case Java

favoriteLanguage = Setting<Languages>(key: "favoriteLanguage", defaultValue: .ObjectiveC)
favoriteLanguage.value = .Swift

With SE-0143 being implemented into Swift 4, the above approach would also work nicely with Arrays and Dictionaries. For any implementation details please refer to https://github.com/oliverschaefer/Settings. Before proceeding with a SE proposal, I’d like to hear your opinion. So thanks for taking your time to look at my code in advance.