Last active
November 13, 2022 23:13
-
-
Save jeksys/dc31ad999e30fd25a76da97f4611d46a to your computer and use it in GitHub Desktop.
This file contains 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
protocol Storable { | |
func get<T: Codable>(key: String) -> T? | |
func remove(for key: String) | |
func add<T: Codable>(object: T, key: String) | |
func update<T: Codable>(object: T, key: String) | |
} | |
class UserDefaultsStorage: Storable { | |
static let shared = UserDefaultsStorage() | |
let storage = UserDefaults.standard | |
func add<T: Codable>(object: T, key: String) { | |
do { | |
let encoded = try JSONEncoder().encode(object) | |
storage.set(encoded, forKey: key) | |
} catch { | |
} | |
} | |
func remove(for key: String) { | |
storage.removeObject(forKey: key) | |
} | |
func update<T: Codable>(object: T, key: String) { | |
remove(for: key) | |
add(object: object, key: key) | |
} | |
func get<T: Codable>(key: String) -> T? { | |
if let object = storage.object(forKey: key) as? Data { | |
return try? JSONDecoder().decode(T.self, from: object) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment