Created
April 24, 2020 13:34
-
-
Save nekonora/06a64fd1fd4622d5fb6dc61cea76e964 to your computer and use it in GitHub Desktop.
A useful little storage class for anything conforming to Codable, using UserDefaults and property wrappers
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
// | |
// Storage.swift | |
// | |
import Foundation | |
class Storage { | |
// MARK: - Keys | |
enum StorageKey: String { | |
case myValue | |
} | |
// MARK: - Properties | |
@Stored<String>(.myValue) | |
static var myValue: String? | |
// MARK: - Methods | |
static func removeData(for keys: Set<StorageKey>) { | |
if keys.contains(.myValue) { myValue = nil } | |
} | |
} | |
@propertyWrapper struct Stored<T: Codable> { | |
let key: Storage.StorageKey | |
let defaultValue: T? | |
init(_ key: Storage.StorageKey, defaultValue: T? = nil) { | |
self.key = key | |
self.defaultValue = defaultValue | |
} | |
var wrappedValue: T? { | |
get { | |
guard let data = UserDefaults.standard.object(forKey: key.rawValue) as? Data else { return defaultValue } | |
let value = try? JSONDecoder().decode(T.self, from: data) | |
return value ?? defaultValue | |
} | |
set { | |
let data = try? JSONEncoder().encode(newValue) | |
UserDefaults.standard.set(data, forKey: key.rawValue) | |
UserDefaults.standard.synchronize() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment