Advertisement
Larme

Untitled

Dec 5th, 2021
1,342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.55 KB | None | 0 0
  1. func customCodableEnum() {
  2.  
  3.     struct SubJSON: Codable {
  4.         let subJSONKey: String
  5.     }
  6.  
  7.     enum MyEnum<T: Codable>: Codable {
  8.  
  9.         case myCase(key: String, value: T)
  10.         case otherCase(Int)
  11.         case unmanagedCase //Could throw a custom error instead
  12.  
  13.         init(from decoder: Decoder) throws {
  14.             let values = try decoder.singleValueContainer()
  15.             if let asInt = try? values.decode(Int.self) {
  16.                 self = .otherCase(asInt)
  17.             } else {
  18.                 let asDict = try values.decode([String: T].self)
  19.                 if let first = asDict.keys.first {
  20.                     self = .myCase(key: first, value: asDict[first]!)
  21.                 } else {
  22.                     self = .unmanagedCase //Could throw a custom error instead
  23.                 }
  24.             }
  25.         }
  26.     }
  27.  
  28.     do {
  29.         let jsonStr = """
  30.    [3,
  31.     {"Key": {
  32.            "subJSONKey": "SubJSONValue"
  33.        }
  34.     }
  35.    ]
  36.    """
  37.         let json = Data(jsonStr.utf8)
  38.         let enums = try JSONDecoder().decode([MyEnum<SubJSON>].self, from: json)
  39.         enums.forEach {
  40.             switch $0 {
  41.             case .myCase(key: let key, value: let value):
  42.                 print("MyEnum.myCase(key: \(key),  value: \(value))")
  43.             case .otherCase(let intValue):
  44.                 print("MyEnum.otherCase(\(intValue))")
  45.             case .unmanagedCase:
  46.                 print("MyEnum.unmanagedCase")
  47.             }
  48.         }
  49.     } catch {
  50.         print("Error: \(error)")
  51.     }
  52. }
  53.  
  54. customCodableEnum()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement