Skip to content

Instantly share code, notes, and snippets.

@markiv
Last active October 28, 2022 15:08
Show Gist options
  • Save markiv/0d4feab3b6349e4e7eb8edf13a277e13 to your computer and use it in GitHub Desktop.
Save markiv/0d4feab3b6349e4e7eb8edf13a277e13 to your computer and use it in GitHub Desktop.
// Allows us to persist any Codable with @AppStorage and @SceneStorage (via a JSON String).
public protocol RawCodable {
static var emptyJSON: String { get }
}
public extension RawCodable where Self: Codable {
init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let value = (try? JSONDecoder().decode(Self.self, from: data)) else { return nil }
self = value
}
var rawValue: String {
let data = (try? JSONEncoder().encode(self)) ?? Data()
return String(data: data, encoding: .utf8) ?? Self.emptyJSON
}
}
extension Array: RawCodable, RawRepresentable where Element: Codable {
public static var emptyJSON: String { "[]" }
}
extension Dictionary: RawCodable, RawRepresentable where Key == String, Value: Codable {
public static var emptyJSON: String { "{}" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment