[swift-evolution] [Draft] UserDefaults Wrapper

Oliver Schäfer oschaefer.swift at icloud.com
Mon Mar 13 07:18:09 CDT 2017


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

UserDefaultConvertible

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 <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.

Cheers,
Oliver 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170313/4c3d59e5/attachment.html>


More information about the swift-evolution mailing list