Advertisement
Larme

Untitled

Feb 6th, 2024
1,184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.46 KB | None | 0 0
  1. func decodingTypes() {
  2.     let json = """
  3.    [
  4.    {
  5.    "type": "Type1",
  6.    "name": "Name 1"
  7.    },
  8.    {
  9.    "type": "Type2",
  10.    "value": 3
  11.    }
  12.    ]
  13.    """
  14.    
  15.     enum Typing: String, Codable {
  16.         case type1 = "Type1"
  17.         case type2 = "Type2"
  18.     }
  19.    
  20.     struct MetaClass: Codable {
  21.         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
  22.         let holder: Holder
  23.        
  24.         init(from decoder: Decoder) throws {
  25.             let container = try decoder.container(keyedBy: CodingKeys.self)
  26.             self.type = try container.decode(Typing.self, forKey: .type)
  27.             switch type {
  28.             case .type1:
  29.                 self.holder = .named(try .init(from: decoder))
  30.             case .type2:
  31.                 self.holder = .numered(try .init(from: decoder))
  32.             }
  33.         }
  34.     }
  35.    
  36.     //Enum to manage multiple possible objects
  37.     enum Holder: Codable {
  38.         case named(Named)
  39.         case numered(Numered)
  40.     }
  41.  
  42.     struct Named: Codable {
  43.         let type: Typing
  44.         let name: String
  45.     }
  46.    
  47.     struct Numered: Codable {
  48.         let type: Typing
  49.         let value: Int
  50.     }
  51.    
  52.     do {
  53.         let decoded = try JSONDecoder().decode([MetaClass].self, from: Data(json.utf8))
  54.         print(decoded)
  55.     } catch {
  56.         print("Error while decoding: \(error)")
  57.     }
  58. }
  59.  
  60. decodingTypes()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement