Created
October 12, 2022 09:59
-
-
Save iamazhar/c39a59bb2ce9ad97cd033356f0a0a060 to your computer and use it in GitHub Desktop.
User Defaults helper with generics
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 | |
| public final 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