Created
October 16, 2019 01:28
-
-
Save foxfriends/fbfe7971f35e9b6a05ef1b2cdf264564 to your computer and use it in GitHub Desktop.
Type safe wrapper around UserDefaults
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
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