Last active
August 9, 2018 06:07
-
-
Save Gurdeep0602/fecef26969fe32aedcb661487f536855 to your computer and use it in GitHub Desktop.
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
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