Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func decodingTypes() {
- let json = """
- [
- {
- "type": "Type1",
- "name": "Name 1"
- },
- {
- "type": "Type2",
- "value": 3
- }
- ]
- """
- enum Typing: String, Codable {
- case type1 = "Type1"
- case type2 = "Type2"
- }
- struct MetaClass: Codable {
- let type: Typing //You might not really need this var and make a custom CodingKeys for decoding it since it's in the `holder` value
- let holder: Holder
- init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- self.type = try container.decode(Typing.self, forKey: .type)
- switch type {
- case .type1:
- self.holder = .named(try .init(from: decoder))
- case .type2:
- self.holder = .numered(try .init(from: decoder))
- }
- }
- }
- //Enum to manage multiple possible objects
- enum Holder: Codable {
- case named(Named)
- case numered(Numered)
- }
- struct Named: Codable {
- let type: Typing
- let name: String
- }
- struct Numered: Codable {
- let type: Typing
- let value: Int
- }
- do {
- let decoded = try JSONDecoder().decode([MetaClass].self, from: Data(json.utf8))
- print(decoded)
- } catch {
- print("Error while decoding: \(error)")
- }
- }
- decodingTypes()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement