Skip to content

Instantly share code, notes, and snippets.

@wh1pch81n
Created June 29, 2017 01:45
Show Gist options
  • Save wh1pch81n/85dada72c9f1c56c94a0d0aea7da95c5 to your computer and use it in GitHub Desktop.
Save wh1pch81n/85dada72c9f1c56c94a0d0aea7da95c5 to your computer and use it in GitHub Desktop.
A Domain specific UserDefaults wrapper
// This class helps facilitate using non-standard defaults.
// Typically standardDefaults will save into "<bundle_identifier>.plist"
// You can use a different one. The BundleUserDefaults class will save into "BundleUserDefaults.plist"
// This means you can clear it without effecting the standard one.
// Base class that all user defaults inherit from
class MyUserDefaults: NSObject {
public let suiteName: String
public let user_default: UserDefaults
init(suiteName: String) {
self.suiteName = suiteName
user_default = UserDefaults(suiteName: suiteName)!
}
func removeSuite() {
user_default.removeSuite(named: suiteName)
}
}
// Bundle specific.
class BundleUserDefaults: MyUserDefaults {
// includes a shared static property with the suiteName the same as the class name
static let shared = BundleUserDefaults(suiteName: "BundleUserDefaults")
// accessor methods. Use of #function assumes the string "m"
var m: String {
get { return user_default.string(forKey: #function) ?? "" }
set { user_default.set(newValue, forKey: #function) }
}
var x: Int {
get { return user_default.integer(forKey: #function) }
set { user_default.set(newValue, forKey: #function) }
}
}
/// Usage
BundleUserDefaults.shared.m = "dog"
BundleUserDefaults.shared.x = 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment