Advertisement
Guest User

Untitled

a guest
Sep 14th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.49 KB | None | 0 0
  1. {
  2.     "from": "Guille",
  3.     "text": "Look what I just found!",
  4.     "attachments": [
  5.         {
  6.             "type": "image",
  7.             "payload": {
  8.                 "url": "http://via.placeholder.com/640x480",
  9.                 "width": 640,
  10.                 "height": 480
  11.             }
  12.         },
  13.         {
  14.             "type": "audio",
  15.             "payload": {
  16.                 "title": "Never Gonna Give You Up",
  17.                 "url": "https://audio.com/NeverGonnaGiveYouUp.mp3",
  18.                 "shouldAutoplay": true,
  19.             }
  20.         }
  21.     ]
  22. }
  23.  
  24. struct ImageAttachment: Codable {
  25.     let url: URL
  26.     let width: Int
  27.     let height: Int
  28. }
  29. struct AudioAttachment: Codable {
  30.     let title: String
  31.     let url: URL
  32.     let shouldAutoplay: Bool
  33. }
  34.  
  35. enum Attachment {
  36.   case image(ImageAttachment)
  37.   case audio(AudioAttachment)
  38.   case unsupported
  39. }
  40.  
  41. extension Attachment: Codable {
  42.   private enum CodingKeys: String, CodingKey {
  43.     case type
  44.     case payload
  45.   }
  46.   init(from decoder: Decoder) throws {
  47.     let container = try decoder.container(keyedBy: CodingKeys.self)
  48.     let type = try container.decode(String.self, forKey: .type)
  49.     switch type {
  50.     case "image":
  51.       let payload = try container.decode(ImageAttachment.self, forKey: .payload)
  52.       self = .image(payload)
  53.     case "audio":
  54.       let payload = try container.decode(AudioAttachment.self, forKey: .payload)
  55.       self = .audio(payload)
  56.     default:
  57.       self = .unsupported
  58.     }
  59.   }
  60.   ...
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement