Skip to content

Instantly share code, notes, and snippets.

@foxfriends
Created October 16, 2019 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxfriends/fbfe7971f35e9b6a05ef1b2cdf264564 to your computer and use it in GitHub Desktop.
Save foxfriends/fbfe7971f35e9b6a05ef1b2cdf264564 to your computer and use it in GitHub Desktop.
Type safe wrapper around UserDefaults
import Foundation
// MARK: - Storage Key
protocol StorageKey {
associatedtype V: Codable
static var key: String { get }
}
// MARK: - Storage
/// Type safe wrapper around the User Defaults
enum Storage {
static func contains<K: StorageKey>(_ key: K.Type) -> Bool {
return UserDefaults.standard.data(forKey: K.key) != nil
}
static func store<K: StorageKey>(value: K.V, for key: K.Type) {
let json = try! JSONEncoder().encode(Box(v: value))
UserDefaults.standard.set(json, forKey: K.key)
}
static func retrieve<K: StorageKey>(_ key: K.Type) -> K.V? {
if let data = UserDefaults.standard.data(forKey: K.key) {
return (try? JSONDecoder().decode(Box<K.V>.self, from: data))?.v
} else {
return nil
}
}
static func remove<K: StorageKey>(_ key: K.Type) {
UserDefaults.standard.removeObject(forKey: K.key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment