Last active
June 3, 2019 11:34
-
-
Save balrajOla/ee1eb9d60efe55c8a9274caf8ab79ea7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Enum with type as type of the content | |
// Assciated value will hold the actual content data | |
enum BodyContent { | |
case number(Int) | |
case text(String) | |
case unsupported | |
} | |
// Now we can represent our Models as | |
struct Content: Decodable { | |
var body: [BodyContent] | |
} | |
// We need to implement Decodable protocol for this enum | |
extension BodyContent: Decodable { | |
private enum CodingKeys: String, CodingKey { | |
case type | |
case content | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
let type = try container.decode(String.self, forKey: .type) | |
switch type { | |
case "int": | |
let payload = try? container.decode(Int.self, forKey: .content) | |
self = payload.map { .number($0) } ?? .unsupported | |
case "string": | |
let payload = try? container.decode(String.self, forKey: .content) | |
self = payload.map { .text($0) } ?? .unsupported | |
default: | |
self = .unsupported | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment