Modern interface to UserDefaults + Codable support
Modern interface to UserDefaults + Codable support
Defaultis a library that extends what
UserDefaultscan do by providing extensions for saving custom objects that conform to
Codableand also providing a new interface to UserDefaults described below, via the protocol
DefaultStorable. You can use only the
Codablesupport extensions or the
DefaultStorableprotocol extensions or both. (or none, that's cool too)
UserDefaultsthat conform to
Codable
UserDefaultswith
DefaultStorable
Feel free to open an Issue requesting the feature you want or send over a pull request!
This library has Storing keys and values in defaults the normal way is error prone because typing out the string value for a key every time leaves the possibility of mistyped keys and keeping track of which keys are used and what is currently stored in
UserDefaultsis somewhat hard. Defining objects specifically for storing in user defaults makes the job of keeping track of what is currently being stored in
UserDefaultsas simple as searching the project's source code for instances that conform to
DefaultStorable. Using objects specifically for storing a set of data in UserDefaults allows settings for a certain piece of data to be logically grouped together.
DefaultStorable- A better way of interacting with
UserDefaults
Instead of manually adding key values to the key store or having to implement
NSCodingmanually and bloating up object code, you can simply and clearly define defaults objects with a clear intent of being used as a means of storing defaults.
Much like how conforming to
Codablegets you a lot for free, so does conforming to
DefaultStorable. **The object conforming to
DefaultStorablemust also conform to
Codable:
Say we want to store theme settings in
UserDefaults(fair enough right?) we first define our object conforming to
Codableand
DefaultStorable.
DefaultStorable
struct VisualSettings: Codable, DefaultStorable { let themeName: String let backgroundImageURL: URL? }
UserDefaults
let settings = VisualSettings(themeName: "bright", backgroundImageURL: URL(string: "https://...")) settings.write()
If you need to save the data under a different key other than the default key (the type name, in this case
"VisualSettings") then this can be achieved by providing the optional argument to
write(withKey:):
swift let settings = VisualSettings(themeName: "bright", backgroundImageURL: URL(string: "https://...")) settings.write(withKey: "someUniqueKey")
if let settings = VisualSettings.read() { // Do something }
If you saved the default under a unque key then it can be read back by providing the optional argument to
read(forKey:):
if let settings = VisualSettings.read(forKey: "someUniqueKey") { // Do something }
CodableSupport
This library offers support for directly storing custom objects within
UserDefaultsthat conform to
Codable. With the release of Swift 4 comes the
Codableprotocol, which provides support for serializing objects.
UserDefaultshas not been updated to work with Swift 4's
Codableprotocol so if saving custom objects directly to
UserDefaultsis necessary then that object must support
NSCodingand inherit from
NSObject.
// 1: Declare object (just conform to Codable, getting default encoder / decoder implementation for free) struct VolumeSetting: Codable { let sourceName: String let value: Double }let setting = VolumeSetting(sourceName: "Super Expensive Headphone Amp", value: 0.4) let key: String = String(describing: VolumeSetting.self)
// 2: Write UserDefaults.standard.df.store(setting, forKey: key)
// 3: Read UserDefaults.standard.df.fetch(forKey: key, type: VolumeSetting.self)
If the default behaviour of
Defaultdoes not quite fit your needs, then any of the default implementation details can be overridden.
The most commonly overridden properties are
defaultIdentifierand
defaults.
defaultIdentifier
defaultIdentifieris the key by which your object will be stored. This defaults to the type name of the object being stored.
public static var defaultIdentifier: String { return String(describing: type(of: self)) }
defaults
defaultswill return the
UserDefaultsdatabase that your application will store defaults objects in. The default implementation returns
UserDefaults.standard
public static var defaults: UserDefaults { return UserDefaults.standard }
UserDefaultsrequires custom types to confrom to NSCoding and be a subclass of
NSObject. Doing that is a little time consuming, and conforming to
NSCodingrequires implementing Decoding / Encoding methods that take a bit of code to implement. The good news is that
Dataconforms to
NSCodingso if you can find a way to convert your object to
Datathen you can store it in
UserDefaults, The
Codableprotocol in Swift 4 does just that! This library takes advantage of the
Codableprotocol introduced in Swift 4. The way it works is by taking an object that conforms to
Codableand encoding it into a
Dataobject which can then be stored in
UserDefaults, then when you want to read it back out again just convert using
Codableagain!
It's that Simple!
If you use Carthage to manage your dependencies, simply add Default to your
Cartfile:
github "Nirma/Default"
If you use Carthage to build your dependencies, make sure you have added
Default.frameworkto the "Linked Frameworks and Libraries" section of your target, and have included
Default.frameworkin your Carthage framework copying build phase.
If you use CocoaPods to manage your dependencies, simply add Default to your
Podfile:
pod 'Default'
Contributions are more than welcome!
Default is free software, and may be redistributed under the terms specified in the LICENSE file.