Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created April 12, 2017 02:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/562e19a4444baf6df44e7e55c466f4e1 to your computer and use it in GitHub Desktop.
Save Ben-G/562e19a4444baf6df44e7e55c466f4e1 to your computer and use it in GitHub Desktop.
User Defaults Wrapper Swift
/// A wrapper around `NSUserDefaults` access for settings that are specific to the PlanGrid app.
/// `NSUserDefaults` should always be accessed through this type, this way we have a good overview
/// of all the settings the app supports and we can document them.
@objc final class PlanGridUserDefaults: NSObject {
/// Keeps track of whether or not a user has already used the annotation filter feature.
static var hasUsedAnnotationFilterFeature = UserDefaultsProperty<Bool>("HasUsedAnnotationFilterFeature")
}
/// A property that wraps around a value that is persisted to NSUserDefaults.
final class UserDefaultsProperty<T> {
let identifier: String
init(_ identifier: String) {
self.identifier = identifier
}
// Would like to make the value property non-optional. But that depends on a fix/workaround
// for https://bugs.swift.org/browse/SR-4479.
var value: T? {
set {
UserDefaults.standard.set(newValue, forKey: self.identifier)
}
get {
return UserDefaults.standard.object(forKey: self.identifier) as? T
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment