Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import Foundation
  2.  
  3. /// Simple example of decoding different values based on a "type" field
  4.  
  5. let json = Data("""
  6. [{
  7. "type": "user",
  8. "name": "Alice"
  9. },
  10. {
  11. "type": "document",
  12. "path": "/etc/passwd"
  13. }
  14. ]
  15. """.utf8)
  16.  
  17. struct User: Codable {
  18. let name: String
  19. }
  20.  
  21. struct Document: Codable {
  22. let path: String
  23. }
  24.  
  25. enum Item {
  26. case user(User)
  27. case document(Document)
  28. }
  29.  
  30. extension Item: Codable {
  31. enum CodingKeys: CodingKey {
  32. case type
  33. }
  34.  
  35. init(from decoder: Decoder) throws {
  36. let container = try decoder.container(keyedBy: CodingKeys.self)
  37. let type = try container.decode(String.self, forKey: .type)
  38.  
  39. // The important point here is that you can extract a second container with a different
  40. // CodingKey from the same decoder.
  41. switch type {
  42. case "user": self = .user(try User(from: decoder))
  43. case "document": self = .document(try Document(from: decoder))
  44. default: throw DecodingError.dataCorruptedError(forKey: .type, in: container,
  45. debugDescription: "Unknown type")
  46. }
  47. }
  48.  
  49. func encode(to encoder: Encoder) throws {
  50. var container = encoder.container(keyedBy: CodingKeys.self)
  51. switch self {
  52. case .user(let user):
  53. // And similarly, you can just keep encoding other stuff into the current encoder.
  54. try container.encode("user", forKey: .type)
  55. try user.encode(to: encoder)
  56. case .document(let document):
  57. try container.encode("document", forKey: .type)
  58. try document.encode(to: encoder)
  59. }
  60. }
  61. }
  62.  
  63. let items = try JSONDecoder().decode([Item].self, from: json)
  64. print(items)
  65.  
  66. let output = try JSONEncoder().encode(items)
  67. print(String(data: output, encoding: .utf8)!)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement