I have the following JSON object:
[{
\"type\": \"foo\",
\"props\": {
\"word\": \"hello\"
}
}, {
\"type\": \"bar\",
\"props\": {
Looking at your original listed errors, there are two distinct issues.
Codable
, but the errors are telling you it cannot automatically synthesize Encodable
. Your question isn't about encoding, but decoding, so for this I'd say just conform to Decodable
instead of Codable
(or implement encoding yourself).props
is of type PropTypes?
, where PropTypes
is an enum. You're decoding either FooProps
or BarProps
, and stuffing the result into props
. You need to wrap the result in the enum instead. Also your enum is defined wrong, you have cases named FooProps
and BarProps
, which don't carry values. It should be redefined like { case foo(FooProps), bar(BarPros) }
instead.So together, this would look like
struct MyObject : Decodable {
struct FooProps : Decodable { let word: String }
struct BarProps : Decodable { var number: Int }
enum PropTypes { case foo(FooProps), bar(BarProps) }
let type: String
let props: PropTypes?
enum CodingKeys : CodingKey {
case type, props
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
type = try values.decode(String.self, forKey: .type)
switch type {
case "foo":
props = try .foo(values.decode(FooProps.self, forKey: .props))
case "bar":
props = try .bar(values.decode(BarProps.self, forKey: .props))
default:
props = nil
}
}
}