Skip to content

Instantly share code, notes, and snippets.

@iamazhar
Last active June 29, 2023 22:42
Show Gist options
  • Save iamazhar/2729989d9b08758f8098d08428c80db9 to your computer and use it in GitHub Desktop.
Save iamazhar/2729989d9b08758f8098d08428c80db9 to your computer and use it in GitHub Desktop.
User Defaults helper that provides core operations
public class UserDefaultsHelper {
/// Use this generic func to encode and save an Codable object to UserDefaults
/// - Parameters:
/// - value: Any Codable type
/// - key: The corresponding key
/// - Returns: true if it is saved successfully, else false
@discardableResult
public static func save<T: Codable>(customValue value: T, withKey key: String) -> Bool {
if let encoded = try? JSONEncoder().encode(value) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: key)
return true
}
return false
}
/// Use this generic func to fetch and decode a Codable object from UserDefaults
/// - Parameters:
/// - type: Any Codable type
/// - key: The key used to look-up the object
/// - Returns: An optional object of any Codable type
public static func fetch<T: Codable>(valueOfType type: T.Type, usingKey key: String) -> T? {
if let savedValue = UserDefaults.standard.object(forKey: key) as? Data {
if let loadedValue = try? JSONDecoder().decode(T.self, from: savedValue) {
return loadedValue
}
}
return nil
}
public static func removeValue(withKey key: String) {
let prefs = UserDefaults.standard
prefs.removeObject(forKey: key)
}
@discardableResult
public static func removeAllFromAppDomain() -> Bool {
if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment