Skip to content

Instantly share code, notes, and snippets.

@Gurdeep0602
Last active August 9, 2018 06:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gurdeep0602/fecef26969fe32aedcb661487f536855 to your computer and use it in GitHub Desktop.
Save Gurdeep0602/fecef26969fe32aedcb661487f536855 to your computer and use it in GitHub Desktop.
import Foundation
import SwiftyJSON
enum AppUserDefaults {
enum Key : String {
case Name
case Age
}
}
extension AppUserDefaults {
static func value(forKey key: Key, file : String = #file, line : Int = #line, function : String = #function) -> JSON {
guard let value = UserDefaults.standard.object(forKey: key.rawValue) else {
fatalError("No Value Found in UserDefaults\nFile : \(file) \nLine Number : \(line) \nFunction : \(function)")
}
return JSON(value)
}
static func value<T>(forKey key: Key, fallBackValue : T, file : String = #file, line : Int = #line, function : String = #function) -> JSON {
guard let value = UserDefaults.standard.object(forKey: key.rawValue) else {
print("No Value Found in UserDefaults\nFile : \(file) \nFunction : \(function)")
return JSON(fallBackValue)
}
return JSON(value)
}
static func save(value : Any, forKey key : Key) {
UserDefaults.standard.set(value, forKey: key.rawValue)
UserDefaults.standard.synchronize()
}
static func removeValue(forKey key : Key) {
UserDefaults.standard.removeObject(forKey: key.rawValue)
UserDefaults.standard.synchronize()
}
static func removeAllValues() {
let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)
UserDefaults.standard.synchronize()
}
}
/* USAGE :
AppUserDefaults.save(value: 32, forKey: .Age)
let age = AppUserDefaults.value(forKey: .Age).intValue
AppUserDefaults.save(value: "Chris", forKey: .Name)
let name = AppUserDefaults.value(forKey: .Age).stringValue
let name = AppUserDefaults.value(forKey: .Name, fallBackValue: "NO NAME")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment