Skip to content

Instantly share code, notes, and snippets.

@cemaleker
Created May 25, 2023 11:08
Show Gist options
  • Save cemaleker/882bb90572503a1d60b29b7c3d89c41c to your computer and use it in GitHub Desktop.
Save cemaleker/882bb90572503a1d60b29b7c3d89c41c to your computer and use it in GitHub Desktop.
Using SwiftUI AppStorage to cache Codable entities
import Foundation
struct JSONStringRawRepresentable<T: Codable>: RawRepresentable {
typealias RawValue = String
var value: T
init(value: T) {
self.value = value
}
init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode(T.self, from: data) else { return nil }
self = .init(value: result)
}
var rawValue: String {
guard let data = try? JSONEncoder().encode(value),
let result = String(data: data, encoding: .utf8) else {
return String()
}
return result
}
}
struct Foo: Codable {
// ...
}
struct YourView: View {
typealias CachedFoo = JSONStringRawRepresentable<[Foo]>
@AppStorage("cachedFoo") var cachedFoo: CachedFoo = .init(value: [])
var body: some View {
// Make a list from your cached Stuff
List(cachedFoo.value, id: \.self) { foo in
Text(foo)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment