Created
May 25, 2023 11:08
-
-
Save cemaleker/882bb90572503a1d60b29b7c3d89c41c to your computer and use it in GitHub Desktop.
Using SwiftUI AppStorage to cache Codable entities
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
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 | |
} | |
} |
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
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