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 | |
| // Inspired by https://gist.github.com/mbuchetics/c9bc6c22033014aa0c550d3b4324411a | |
| struct JSONCodingKeys: CodingKey { | |
| var stringValue: String | |
| init?(stringValue: String) { | |
| self.stringValue = stringValue | |
| } |
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 | |
| @dynamicMemberLookup | |
| enum JSON: Codable, CustomStringConvertible { | |
| var description: String { | |
| switch self { | |
| case .string(let string): return "\"\(string)\"" | |
| case .number(let double): | |
| if let int = Int(exactly: double) { | |
| return "\(int)" |
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 User: Codable { | |
| var name: String | |
| var email: String | |
| var id: String | |
| var metadata: [String: MetadataType] | |
| enum CodingKeys: String, CodingKey { | |
| case name, email, id, metadata | |
| } | |
| } |
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
| enum JSON: Decodable { | |
| case bool(Bool) | |
| case double(Double) | |
| case string(String) | |
| indirect case array([JSON]) | |
| indirect case dictionary([String: JSON]) | |
| init(from decoder: Decoder) throws { | |
| if let container = try? decoder.container(keyedBy: JSONCodingKeys.self) { | |
| self = JSON(from: container) |