Last active
October 28, 2022 15:08
-
-
Save markiv/0d4feab3b6349e4e7eb8edf13a277e13 to your computer and use it in GitHub Desktop.
This file contains 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
// 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