Created
June 3, 2019 12:14
-
-
Save balrajOla/25dbc11987e747819b5d9a2b701770e7 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
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