Created
April 12, 2017 02:04
-
-
Save Ben-G/562e19a4444baf6df44e7e55c466f4e1 to your computer and use it in GitHub Desktop.
User Defaults Wrapper Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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