Guest User

Untitled

a guest
May 18th, 2020
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.87 KB | None | 0 0
  1. import UIKit
  2.  
  3. var json = """
  4. {
  5.  "type": "int",
  6.  "value": 1
  7. }
  8. """
  9.  
  10. struct MyString: Codable {
  11.     let value: String
  12.     enum keys: CodingKey {
  13.         case value
  14.     }
  15. }
  16. struct MyInt: Codable {
  17.     let value: Int
  18. }
  19.  
  20. struct TypeContainer: Decodable {
  21.     let type: SupportedType
  22.     enum SupportedType: String, Codable {
  23.         case string
  24.         case int
  25.     }
  26. }
  27.  
  28. do {
  29.     let typeContainer = try JSONDecoder().decode(TypeContainer.self, from: json.data(using: .utf8)!)
  30.    
  31.     switch typeContainer.type {
  32.     case .string:
  33.         let string = try JSONDecoder().decode(MyString.self, from: json.data(using: .utf8)!)
  34.         print("string value: \(string.value)")
  35.     case .int:
  36.         let int = try JSONDecoder().decode(MyInt.self, from: json.data(using: .utf8)!)
  37.         print("int value: \(int.value)")
  38.     }
  39. } catch {
  40.     print(error)
  41. }
Advertisement
Add Comment
Please, Sign In to add comment