Skip to content

Instantly share code, notes, and snippets.

@jeksys
Last active November 13, 2022 23:13
Show Gist options
  • Save jeksys/dc31ad999e30fd25a76da97f4611d46a to your computer and use it in GitHub Desktop.
Save jeksys/dc31ad999e30fd25a76da97f4611d46a to your computer and use it in GitHub Desktop.
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