Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save balrajOla/25dbc11987e747819b5d9a2b701770e7 to your computer and use it in GitHub Desktop.
Save balrajOla/25dbc11987e747819b5d9a2b701770e7 to your computer and use it in GitHub Desktop.
struct Content: Decodable {
var body: [Body]
}
protocol BodyContent: Decodable {
func getContent<T: Decodable>() -> T?
}
struct Body: Decodable {
var type: String
var content: BodyContent?
private enum CodingKeys: String, CodingKey {
case type
case content
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.type = try container.decode(String.self, forKey: .type)
switch type {
case "string":
let contentData = try? container.decode(String.self, forKey: .content)
self.content = contentData.map { ContentData(content: $0) }
break
case "int":
let contentData = try? container.decode(Int.self, forKey: .content)
self.content = contentData.map { ContentData(content: $0) }
default:
self.content = nil
}
}
}
struct ContentData<T: Decodable>: BodyContent {
let content: T
func getContent<R>() -> R? where R: Decodable {
return (content as? R)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment