Created
July 18, 2020 02:04
-
-
Save emma-k-alexandra/1a2ed9e7bb5b35ded5875271b9e96609 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Content: Codable { | |
let content: [Element] | |
enum Element: Codable { | |
case header(Header) | |
case paragraph(Paragraph) | |
case footer(Footer) | |
struct Header: Codable { | |
let title: String | |
let level: Int | |
} | |
struct Paragraph: Codable { | |
let text: String | |
} | |
struct Footer: Codable { | |
let style: String | |
let copyright: String | |
} | |
struct BaseContent: Codable { | |
let type: ContentType | |
enum ContentType: String, Codable { | |
case header | |
case paragraph | |
case footer | |
} | |
enum CodingKeys: String, CodingKey { | |
case type | |
} | |
} | |
init(from decoder: Decoder) throws { | |
let baseContainer = try decoder.container(keyedBy: BaseContent.CodingKeys.self) | |
let type = try baseContainer.decode(BaseContent.ContentType.self, forKey: .type) | |
let container = try decoder.singleValueContainer() | |
switch type { | |
case .header: | |
self = .header(try container.decode(Header.self)) | |
case .paragraph: | |
self = .paragraph(try container.decode(Paragraph.self)) | |
case .footer: | |
self = .footer(try container.decode(Footer.self)) | |
} | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .header(let header): | |
try container.encode(header) | |
case .paragraph(let paragraph): | |
try container.encode(paragraph) | |
case .footer(let footer): | |
try container.encode(footer) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment