Created
November 14, 2022 03:51
-
-
Save thanakijwanavit/6ea944bb1b38c85d98096e0328b5d23b to your computer and use it in GitHub Desktop.
extension for makinkg codable array conform to appstorage
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
extension Array: RawRepresentable where Element: Codable { | |
public init?(rawValue: String) { | |
guard let data = rawValue.data(using: .utf8), | |
let result = try? JSONDecoder().decode([Element].self, from: data) | |
else { | |
return nil | |
} | |
self = result | |
} | |
public var rawValue: String { | |
guard let data = try? JSONEncoder().encode(self), | |
let result = String(data: data, encoding: .utf8) | |
else { | |
return "[]" | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment