Skip to content

Instantly share code, notes, and snippets.

@MaximBazarov
Created October 10, 2024 07:43
Show Gist options
  • Save MaximBazarov/7445b9e0f760603669359c4156ce8c63 to your computer and use it in GitHub Desktop.
Save MaximBazarov/7445b9e0f760603669359c4156ce8c63 to your computer and use it in GitHub Desktop.
Storage for an array of Coddle items on disk
import UIKit
enum StoredItem<V: Codable> {
case item(key: String, value: V)
case delete(key: String)
init(key: String, value: V?) {
self = .delete(key: key)
}
init(key: String, value: V) {
self = .item(key: key, value: value)
}
var key: String {
switch self {
case .item(let key, _), .delete(let key):
return key
}
}
}
let point: CGPoint? = nil
let store = StoredItem(key: "point", value: point)
let point2: CGPoint = .zero
let store2 = StoredItem(key: "point2", value: point2)
func saveToDisk<V: Codable>(item: StoredItem<V>) {
switch item {
case .item(let key, let value):
let data = try? JSONEncoder().encode(value)
UserDefaults.standard.set(data, forKey: key)
case .delete(let key):
UserDefaults.standard.removeObject(forKey: key)
}
}
extension StoredItem {
func loadFromDisk() -> V? {
guard let data = UserDefaults.standard.data(forKey: key) else { return nil }
return try? JSONDecoder().decode(V.self, from: data)
}
}
let myArrayToStore = [store, store2]
myArrayToStore.forEach(saveToDisk(item:))
myArrayToStore.forEach { item in
print(item.loadFromDisk() ?? "Item with \(item.key) not found")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment